XAML 101: The StackPanel

FacebookTwitterGoogle+Share

Source code for this sample on GitHub: https://github.com/billreiss/xamlnative/tree/master/Xaml101/010_StackPanel

So far when looking at elements that contain other elements we have seen the Border and the Grid. Another useful container is the StackPanel. If you are familiar with Android development, the closest relation is to the LinearLayout control. The StackPanel lets you arrange elements in sequence one after the other either vertically or horizontally.

NOTE: When I was working closely with designers in Silverlight (a XAML based framework) they would usually take my StackPanels and convert them to Grids with Rows or Columns, they liked the level of control they had over the layout better. There are some drawbacks to StackPanel especially when it comes to horizontal StackPanels and fitting the available space. It’s usually not as much of a problem vertically and it is more common to use StackPanel in vertical mode. The StackPanel is an important component of ListView and other list based controls we will see later.

In the last post we had some text in the grid, but what if we wanted a few lines of text. One way to do this is to use a StackPanel:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <TextBlock Text="Here is some text"/>
        <TextBlock Text="Some more text"/>
        <TextBlock Text="3rd line of text"/>
    </StackPanel>
</Grid>

And this is how it looks:

image

The Orientation property on the StackPanel defaults to Vertical but we can change it to Horizontal:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Here is some text"/>
        <TextBlock Text="Some more text"/>
        <TextBlock Text="3rd line of text"/>
    </StackPanel>
</Grid>

And here is how it looks:

image

I haven’t seen many cases where a Horizontal StackPanel is the best option. Usually there is a better solution, it could be a Grid with Columns, or a RelativePanel, we will see the RelativePanel soon.