For the complete documentation index, see llms.txt. This page is also available as Markdown.

StackPanel

Introduction

StackPanel is a container used to for controls which should stack vertically or horizontally, and which supports wrapping. StackPanels do not include any visual so they are always invisible.

Backgrounds

StackPanels do not include any visuals, so they are always invisible on their own. To add a visible background behind a StackPanel, wrap it in a Panel with a ColoredRectangleRuntime. For details and a code example, see Adding Backgrounds to Layout Containers.

Code Example: Adding Buttons to a StackPanel

The following code shows how to add Button instances to a StackPanel. Notice that each button is automatically stacked vertically.

// Initialize
var stackPanel = new StackPanel();
stackPanel.AddToRoot();
stackPanel.X = 50;
stackPanel.Y = 50;
stackPanel.Width = 200;

var random = new System.Random();
for (int i = 0; i < 10; i++)
{
    var button = new Button();
    stackPanel.AddChild(button);
    button.Text = "Button " + i;
    button.Height = 36;
    button.Click += (_, _) =>
        button.Text = DateTime.Now.ToString();
}

Try on XnaFiddle.NET

Stack Panel Sizing

By default StackPanels contain a Visual with the following properties:

  • WidthUnits = Absolute

  • HeightUnits = RelativeToChildren

This means that as more children are added to a StackPanel, the StackPanel grows vertically.

The following code creates a main StackPanel with two internal StackPanels. Each internal StackPanel contains a Button which can be used to add labels to the respective internal StackPanel.

Try on XnaFiddle.NET

Orientation

StackPanel Orientation controls whether items in a StackPanel are positioned top-to-bottom or left-to-right. Changing the StackPanel Orientation property changes the internal visual's ChildrenLayout property. For more information on ChildrenLayout see the ChildrenLayout page.

WidthUnits and HeightUnits are not changed when changing Orientation. If you want the StackPanel instance to grow horizontally when changing Orientation to Horizontal, you need to modify the WidthUnits and HeightUnits.

The following code creates a horizontal StackPanel with buttons stacked left-to-right.

Try on XnaFiddle.NET

Children

StackPanel children can be directly accessed through its Visual.Children property.

For example, the following code shows how to randomize items in a StackPanel.

Try on XnaFiddle.NET

Last updated

Was this helpful?