So let's create a new WPF application, and replace the default <Grid> with a <StackPanel> of CheckBoxes. Your MainWindow's XAML code should look something like this:
Title="MainWindow" Height="350" Width="525">
<TextBlock>Choose the pizzas you want to order:</TextBlock>
<CheckBox>Ham and Mushroom</CheckBox>
As we saw in yesterday's article, a <StackPanel> will lay out any controls inside it as a vertical list by default. You should be able to see this in Visual Studio's preview:
That's because the <StackPanel> has an Orientation property, which by default is set to Vertical. See what happens when we change this to Horizontal:
So as you can see, the <StackPanel> is also useful to position controls horizontally next to each other.
However, as you can see from the preview, we have so many checkboxes that they didn't all fit in the 525-pixel-wide window, so that the ones further right can't be seen because they fall outside the window's boundaries.
Let us now see what happens if we change the <StackPanel> to a <WrapPanel>:
So the <WrapPanel> is actually quite similar to the <StackPanel>, but there are two main differences. The first, as you've probably noticed, is that a <WrapPanel> will wrap controls that don't fit on one line onto subsequent lines.
The second is that a <WrapPanel>'s Orientation is Horizontal by default. You can change it to Vertical to have controls listed and wrapping vertically instead. Let's add a bunch of other checkboxes just to see how this works:
Great! In this article we've seen how to use the <StackPanel> and <WrapPanel> layout controls. Both of these can be used to list items in either vertical or horizontal lists. They are two key differences between them:
- The <StackPanel> will always use keep controls in one row or column, even if they don't fit; the <WrapPanel> will instead wrap controls onto subsequent rows/columns when they don't fit.
- The default Orientation of the <StackPanel> is Vertical, while that of the <WrapPanel> is Horizontal.