#496 – Using a StackPanel to Make a Group of Buttons the Same Size

You’ll often want to stack a group of buttons in a GUI, vertically or horizontally. You’d typically use a StackPanel to do this.

Let’s say that you want a series of buttons stacked vertically on the right side of a window.

We can use a DockPanel as the main container and add a StackPanel docked on the right and oriented vertically. But when we do this, the StackPanel expands to fill the available space, as does each Button.

The HorizontalAlignment of the StackPanel defaults to Stretch, as do each of the buttons. We could set the HorizontalAlignment for each Button to Right, but the buttons now all size to fit their content, which is not quite what we want.

What we really want is for the HorizontalAlignment of each Button to be Stretch, but for the HorizontalAlignment of the StackPanel itself to be Right. This gives us what we want.