HorizontalAlignment
WPF controls can be aligned. With the HorizontalAlignment
and VerticalAlignment
attributes, we anchor controls to edges or center them.
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.
This example shows both HorizontalAlignment
and VerticalAlignment
. The buttons can be seen aligned in the screenshot on this page.
Button
. It is on the left side of the window at the top.Button
has a HorizontalAlignment
of Left, and a vertical one of "Bottom," so it is at the bottom left.Button
will always be located in the center of the window. Try resizing the window: it remained centered.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>
What happens when you specify both HorizontalAlignment
of Stretch, and a Width value? This ends up being the same as Center.
The example only uses Buttons, but many controls support the HorizontalAlignment
and VerticalAlignment
properties. In many ways, all controls are unified in WPF.
HorizontalAlignment
and VerticalAlignment
align controls to one edge of the container. With them, we also can Stretch or Center the controls.