WPF Stack Panel Align Centrally

.net, c#, silverlight, wpf

Solution

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>

Problem

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?

Original source