WPF StackPanel Layout


The StackPanel is easy to use, code and understanding, making it a popular panel. It sequentially arranges controls in a line, either horizontally or vertically. The StackPanel is a container for other controls that handles the layout for you.

Below is an example of a horizontal StackPanel within a vertical StackPanel. In the XAML code below, we’ve used StackPanel’s Orientation property and set it to Vertical or Horizontal. The below code is from the Code Project website in an article called WPF Layouts – A Visual Quick Start.

Here is the code that produces the above screen shot.

    <StackPanel Orientation="Vertical">
        <!-- Vertical is the default -->
        <Label Background="Red">Red 1</Label>
        <Label Background="LightGreen">Green 1</Label>
        <StackPanel Orientation="Horizontal">
            <Label Background="Red">Red 2</Label>
            <Label Background="LightGreen">Green 2</Label>
            <Label Background="LightBlue">Blue 2</Label>
            <Label Background="Yellow">Yellow 2</Label>
            <Label Background="Orange">Orange 2</Label>
        </StackPanel>
        <Label Background="LightBlue">Blue 1</Label>
        <Label Background="Yellow">Yellow 1</Label>
        <Label Background="Orange">Orange 1</Label>
    </StackPanel>