WPF HorizontalAlignment and VerticalAlignment

This WPF example shows the HorizontalAlignment and VerticalAlignment properties. It uses Stretch and Center.

HorizontalAlignment. WPF controls can be aligned.

With the HorizontalAlignment and VerticalAlignment attributes, we anchor controls to edges or center them. We can also stretch controls to fill the available space.

Based on:

.NET 4.5

 

 

Example. This example shows both HorizontalAlignment and VerticalAlignment. I added five Buttons to a Grid in a Window. I left the default Width of each Button, but changed the alignment properties.

ButtonGrid

 

Left, Top: This is the first Button. It is on the left side of the window at the top.

Left, Bottom: This Button has a HorizontalAlignment of Left, and a vertical one of "Bottom," so it is at the bottom left.

Left, Center: The third button is located on the left edge, vertically centered. Its position changes as the window resizes.

Center, Center: This Button will always be located in the center of the window. Try resizing the window: it remained centered.

Right, Stretch: This Button uses Stretch for its VerticalAlignment. This means it expands to fill the vertical space.

Example markup: XAML

<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. The Width value takes precedence over the Stretch value.

 

Tip: To have a control expand to fill the space, remove the "Width" or "Height" properties. They do not need to be specified.

 

Discussion. The example only uses Buttons, but many controls support the HorizontalAlignment and VerticalAlignment properties. In many ways, all controls are unified in WPF. This makes programs easier to build.

 

Note: There are inconsistent parts. For example, a Button uses the "Content" attribute for its text, while a TextBox uses a Text attribute.

 

Summary. HorizontalAlignment and VerticalAlignment align controls to one edge of the container. With them, we also can Stretch or Center the controls. With Stretch, the control is resized to fill the available space.