Enter the StackPanel control, one of the several panels this
article will discuss today. The StackPanel element is responsible for stacking
elements vertically on the screen. However, by adjusting the orientation property,
the StackPanel element can render horizontally too. The prime function of this
element is to stack its children one on top of the other. The StackPanel
doesn't wrap to the next line; this means that the content has to fit, or else
clipping of content may occur. This scenario works will when a Min/Max width
are specified for its children, but even this may not prevent clipping from occuring,
depending on the size of the content and its restrictions.
The StackPanel works by adding one or more children to it,
as any other panel works (even in the ASP.NET work, with the Panel server
control). All of the inner children get positioned accordingly. To solve the
situation desribed above, where the Grid cannot display multiple controls in
the same cell, the StackPanel can be used to save the design as shown in
Listing 4.
Listing 4: Using the StackPanel
<Grid ..>
<TextBlock Grid.Row="5" Grid.Column="0" Text="Contact Numbers" />
<StackPanel Grid.Row="5" Grid.Column="1">
<TextBox Name="PN1" />
<TextBox Name="PN2" />
<TextBox Name="PN3" />
</StackPanel>
</Grid>
Each of the three phone number textboxes renders vertically
within row 5, column 1, because of the StackPanel. Markup becomes easier too
because the StackPanel stores the row/column, not each textbox.
The StackPanel doesn't use attached properties, so implementation
is very straightforward. Because it's very easy to use, this makes for a good
candidate to replace the Grid as the child of the UserControl. In a lot of
situations, I often delete the default Grid child and use a StackPanel
instead. The vertical nature of a page often makes this a prime parent choice.
However, this control wouldn't be as useful in developing forms without the
next control.