user1474992
user1474992

Reputation: 807

WPF Stack Panel Align Centrally

I want to be able to align buttons within a stack panel centrally. The number of buttons is dynamic and generated when the control is loaded. For example, if 1 button is generated then this button should be placed in the center of the control. If 5 buttons are displayed then all 5 should be horizontally aligned next 2 each other but central to the control.

An alternative approach would be to have the control dynamically resize based on its content so it would be wider with more buttons and then horizontally align the user control on the page but I'm not sure how to approach either solution?

Does anybody have any ideas?

Upvotes: 15

Views: 24811

Answers (2)

akjoshi
akjoshi

Reputation: 15772

You can simply set following in XAML

StackPanel.HorizontalAlignment = HorizontalAlignment.Center;

or

HorizontalAlignment="Center" (as GrayFox374 mentioned)

Here is a MSDN sample explaining various alignment operations, having exactly what you need I think - How to: Horizontally or Vertically Align Content in a StackPanel

Upvotes: 8

GrayFox374
GrayFox374

Reputation: 1782

This should work. Set the Horizontal Alignment in the stack panel, and make sure when you are dynamically adding your button, you give them each a margin property value to give them some space from each other. horizontal to each other, central to the control.

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="20">
        <Button Margin="10">one</Button>
        <Button Margin="10">two</Button>
        <Button Margin="10">three</Button>
        <Button Margin="10">four</Button>
        <Button Margin="10">five</Button>            
    </StackPanel>

Upvotes: 25

Related Questions