#577 – You Can Change DockPanel.Dock Property at Runtime

The attached property DockPanel.Dock dictates which side of the remaining space in a DockPanel a child control will dock to.  You typically set DockPanel.Dock in XAML at design time, for each child of the DockPanel.

You can also change any DockPanel.Dock value at runtime.  In the example below, clicking on the button selects new random values for Dock.

		<DockPanel>
		    <Label Name="lbl1" Content="1st label" DockPanel.Dock="Top" Background="Bisque"/>
		    <Label Name="lbl2" Content="2nd" DockPanel.Dock="Left" Background="BurlyWood"/>
		    <Label Name="lbl3" Content="3rd" DockPanel.Dock="Top" Background="Cornsilk"/>
		    <Label Name="lbl4" Content="4th" DockPanel.Dock="Right" Background="DarkKhaki"/>
		    <Label Name="lbl5" Content="5th" DockPanel.Dock="Bottom" Background="DarkSeaGreen"/>
		    <Label Name="lbl6" Content="6th" DockPanel.Dock="Left" Background="Gainsboro"/>
		    <Label Content="7th, fills remaining space" Background="Khaki"/>
		</DockPanel>

 

        private Random randGen = new Random();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DockPanel.SetDock(lbl1, RandomDock());
            DockPanel.SetDock(lbl2, RandomDock());
            DockPanel.SetDock(lbl3, RandomDock());
            DockPanel.SetDock(lbl4, RandomDock());
            DockPanel.SetDock(lbl5, RandomDock());
            DockPanel.SetDock(lbl6, RandomDock());
        }

        private Dock RandomDock()
        {
            return (Dock)randGen.Next(3);
        }




About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment