WPF Control Layout - StackPanel
(Page 2 of 5 )
Perhaps the simplest layout involves placing controls in a vertical or horizontal line. This can also be seen as “stacking” controls—putting one on top of another, or beside another as it's added to the page. This type of layout is possible through a StackPanel. Controls placed within a StackPanel tag will display stacked in the order that you create them. The StackPanel features an Orientation property that can be set to either Vertical or Horizontal. A vertical orientation can produce something like this:

And a horizontal orientation can produce something like this:

The two examples above use almost the exact same code. The only difference is that the Orientation properties are set to different values.
The first example can be reproduced with the following XAML:
<StackPanel Orientation="Vertical">
<Button Content="Button 1" />
<Button Content="Button 2" />
<Button Content="Button 3" />
<Button Content="Button 4" />
</StackPanel>
Above, we explicitly set the Orientation property. However, when stacking things vertically, this actually isn't necessary, since the default value is Vertical. We could have achieved the same results by leaving it out altogether:
<StackPanel>
...
</StackPanel>
The second example can be reproduced simply by changing the value of Orientation:
<StackPanel Orientation="Horizontal">
<Button Content="Button 1" />
<Button Content="Button 2" />
<Button Content="Button 3" />
<Button Content="Button 4" />
</StackPanel>
It's also possible to put one StackPanel within another, if necessary. Using this approach, something like this could be achieved:

<StackPanel Orientation="Vertical">
<Button Content="Button 1" />
<StackPanel Orientation="Horizontal">
<Button Content="Button 2" />
<Button Content="Button 3" />
<Button Content="Button 4" />
</StackPanel>
</StackPanel>
However, for more advanced layouts requiring distinct rows and columns, the Grid layout element, which will be covered later, is a much better choice.
The default value for HorizontalAlignment and VeritcalAlignment for controls within a StackPanel is Stretch. This can produce some odd results (such as the example with a horizontal orientation). So, in some situations, it may be best to change this to a more natural look:

<StackPanel Orientation="Horizontal">
<Button Content="Button 1" VerticalAlignment="Center" />
<Button Content="Button 2" VerticalAlignment="Center" />
<Button Content="Button 3" VerticalAlignment="Center" />
<Button Content="Button 4" VerticalAlignment="Center" />
</StackPanel>
A better way to do this would be to create a style within the StackPanel:
<StackPanel.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</StackPanel.Resources>
Next: WrapPanel >>
More Windows Scripting Articles
More By Peyton McCullough