Reputation: 8506
How can I insert elements into a stackpanel, and they start positioned by center? Something like this:
|_ _ x _ _ |
|_ x x _ _ |
|_ x x x _ |
The "x" are the elements, and the "_" are blank space.
Is there something already implemented?
Upvotes: 11
Views: 24710
Reputation: 1225
You could wrap your elements in a Grid
:
<Grid Width="720">
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Width="Auto" >
<!-- elements go here -->
</StackPanel>
</Grid>
This is the simplest approach in my opinion. You also need to make sure that the StackPanel's Width="Auto" and Grid's Width="720"(some fixed value as needed).
Upvotes: 36
Reputation: 13151
<StackPanel>
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<!-- element x -->
</StackPanel>
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<!-- element x -->
<!-- element x -->
</StackPanel>
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<!-- element x -->
<!-- element x -->
<!-- element x -->
</StackPanel>
<StackPanel>
This produces the example you gave.
Upvotes: 1
Reputation: 96702
Wrap the elements in an element that has HorizontalAlignment
set to Stretch
, e.g.:
<StackPanel>
<Border HorizontalAlignment="Stretch">
<TextBlock Text="something short" HorizontalAlignment="Center"/>
</Border>
<Border HorizontalAlignment="Stretch">
<TextBlock Text="something a bit longer" HorizontalAlignment="Center"/>
</Border>
<Border HorizontalAlignment="Stretch">
<TextBlock Text="something more than a bit longer" HorizontalAlignment="Center"/>
</Border>
</StackPanel>
Upvotes: 1
Reputation: 5828
It depends a bit on the elements you are adding to the StackPanel, but in general look for the following: make sure that each element has the HorizontalAlignment set to Stretch (so they span the entire width) and then set the HorizontalContentAlignment to Center.
Upvotes: 0