HorizontalAlignment and VerticalAlignment
This page was last reviewed on Apr 5, 2023.
Dot Net Perls
HorizontalAlignment. WPF controls can be aligned. With the HorizontalAlignment and VerticalAlignment attributes, we anchor controls to edges or center them.
Getting started. First add several buttons (like 5) to a Grid in a Window. I left the default Width of each Button, but changed the alignment properties.
Example. This example shows both HorizontalAlignment and VerticalAlignment. The buttons can be seen aligned in the screenshot on this page.
Start We see the first Button. It is on the left side of the window at the top.
Next This Button has a HorizontalAlignment of Left, and a vertical one of "Bottom," so it is at the bottom left.
Info The third button is located on the left edge, vertically centered. Its position changes as the window resizes.
And The Center Button will always be located in the center of the window. Try resizing the window: it remained centered.
Finally The final Button uses Stretch for its VerticalAlignment. This means it expands to fill the vertical space.
<Window x:Class="WpfApplication14.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/> <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="75"/> <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Center" Width="75"/> <Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> <Button Content="Button" HorizontalAlignment="Right" VerticalAlignment="Stretch" Width="75"/> </Grid> </Window>
Width. What happens when you specify both HorizontalAlignment of Stretch, and a Width value? This ends up being the same as Center.
And The Width value takes precedence over Stretch. To have a control expand to fill the space, remove the Width or Height properties.
A discussion. The example only uses Buttons, but many controls support the HorizontalAlignment and VerticalAlignment properties. In many ways, all controls are unified in WPF.
A summary. HorizontalAlignment and VerticalAlignment align controls to one edge of the container. With them, we also can Stretch or Center the controls.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 5, 2023 (edit).
© 2007-2024 Sam Allen.