#444 – Children of DockPanel Don’t Always Have to be Stretched
December 6, 2011 Leave a comment
Normally, when you dock a child element in a DockPanel to one of the sides, it is stretched to fit the entire length or height of that side.
<DockPanel> <Button Content="1st (Top)" DockPanel.Dock="Top" /> <Button Content="2nd (Left)" DockPanel.Dock="Left" /> <Button Content="3rd (Top)" DockPanel.Dock="Top" /> <Label Content="4th (Right)" DockPanel.Dock="Right" Background="DarkKhaki"/> <Label Content="5th, fills remaining space" Background="Khaki"/> </DockPanel>
You can, however, use HorizontalAlignment (when docked to Top or Bottom) or VerticalAlignment (when docked to Left or Right) to have the control autosize to fit its content.
<DockPanel> <Button Content="1st (Top/Center)" DockPanel.Dock="Top" HorizontalAlignment="Center"/> <Button Content="2nd (Left/Bottom)" DockPanel.Dock="Left" VerticalAlignment="Bottom"/> <Button Content="3rd (Top/Right)" DockPanel.Dock="Top" HorizontalAlignment="Right"/> <Label Content="4th (Right/Top)" DockPanel.Dock="Right" Background="DarkKhaki" VerticalAlignment="Top"/> <Label Content="5th, fills remaining space, Centered" Background="Khaki" HorizontalAlignment="Center"/> </DockPanel>