WPF stacks panel centered

I want you to be able to align the buttons inside the stack panel centrally. The number of buttons is dynamic and is generated when the control is loaded. For example, if 1 button is created, this button should be placed in the center of the control. If 5 buttons are displayed, all 5 should be horizontally aligned one after the other 2, and central to the control.

An alternative approach would be to control the dynamic resizing based on its contents so that it is wider with a lot of buttons and then horizontally aligns the user control on the page, but I'm not sure how to approach any solution?

Does anyone have any ideas?

+7
source share
2 answers

That should work. Set the horizontal alignment on the stack panel and make sure that when you dynamically add your button, you give them each value of the margin property to give them some space from each other. horizontal to each other, central to 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> 
+16
source

You can simply install the following in XAML

StackPanel.HorizontalAlignment = HorizontalAlignment.Center;

or

HorizontalAlignment="Center" (as mentioned by GreyFox374)

Here is an MSDN example explaining the various alignment operations, having exactly what you need, I think - A practical guide. Horizontal or vertical alignment of content in a StackPanel

+7
source

All Articles