Sabtu, 17 Agustus 2013

WPF: Alignments of Elements

In earlier post we have learnt about size-related properties i.e. Height & Width and Margin & Padding. In this article we will focus on alignments of elements. How a children should be positioned within a parent’s allocated space, is described by Alignment properties of an element.

There are two alignments i.e. Horizontal and Vertical and each one has its individual four values to be assigned.

Horizontal Alignment—Left, Center, Right and Stretch
Vertical Alignment—Top, Center, Bottom and Stretch

Each of these alignments have its own layout which is described below:

Left—Children are aligned to the left of parent’s allocated space.
Right—Children are aligned to the right of parent’s allocated space.
Top—Children are aligned to the top of parent’s allocated space.
Bottom—Children are aligned to the bottom of parent’s allocated space.
Center—Children are aligned to the center of parent’s allocated space.
Stretch—Children are stretched to fill the parent’s allocated space. Default value for alignments.

Place some buttons on a window and use above properties one by one and look out the effects of these alignments.
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Button HorizontalAlignment="Left">Button 1</Button>
<Button HorizontalAlignment="Center">Button 2</Button>
<Button HorizontalAlignment="Right">Button 3</Button>
<Button HorizontalAlignment="Stretch">Button 3</Button>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Button VerticalAlignment="Top" >Button 1</Button>
<Button VerticalAlignment="Center" >Button 2</Button>
<Button VerticalAlignment="Bottom" >Button 3</Button>
<Button VerticalAlignment="Stretch">Button 3</Button>
</StackPanel>
</Grid>
The preceding code yields a layout similar to the following screenshot. Positioning effects of both the alignments are visible.
Element's Horizontal and Vertical Alignment in WPF

Tidak ada komentar:

Posting Komentar