开发者

Elements starting by center of a stackpanel

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?


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).


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>


<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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜