
Margin and Alignment Properties
When a FrameworkElement object is within a panel, the panel functions as a bounding box. The precise position of the object within that bounding box can be specified by setting the Margin, HorizontalAlignment, and VerticalAlignment properties. In the following example, a part of a form is defined by using two nested StackPanel objects.
<StackPanel Background="Coral">
<StackPanel Orientation="Horizontal" >
<TextBlock>First Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<TextBlock>Last Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
</StackPanel>
The following illustration shows how this code renders.
.png)
This layout looks a bit awkward because all the elements are right up against one another and there is no space between the objects and their container. You can use the Margin property to create a margin of space between objects. In the following example, the Margin property is set on the StackPanel objects and the TextBlock objects.
<StackPanel Background="Coral">
<StackPanel Margin="10" Orientation="Horizontal" >
<TextBlock Margin="4">First Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
<StackPanel Margin="10" Orientation="Horizontal" >
<TextBlock Margin="4">Last Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
</StackPanel>
The following diagram shows the effect of the Margin property.
.png)
The Margin property is of type Thickness, which means that you can specify different values for the left, top, right, and bottom margins. For example, in XAML, an object with a margin specified as Margin="10, 5, 20, 30" would have a margin of 10 pixels on the left, 5 on the top, 20 on the right, and 30 on the bottom.
You can also use the HorizontalAlignment and VerticalAlignment properties to position an object within its container area. In the following example, the HorizontalAlignment value of Center is used to position the child StackPanel elements in the center of their parent StackPanel.
<StackPanel Background="Coral">
<StackPanel HorizontalAlignment="Center" Margin="10" Orientation="Horizontal" >
<TextBlock Margin="4">First Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
<StackPanel HorizontalAlignment="Center" Margin="10" Orientation="Horizontal" >
<TextBlock Margin="4">Last Name:</TextBlock>
<TextBox Height="30" Width="180"></TextBox>
</StackPanel>
</StackPanel>
The following diagram shows the effect of the HorizontalAlignment property. Note that the child StackPanel objects have a light blue Background so that you can see the bounding boxes of those StackPanel objects.