views:

509

answers:

2

I need to find a way of absolutely centering the content of a LayoutPanel in WPF. I have two textblock elements which must render at the vertical and horizontal center of the panel without relying on absolute heights and widths.

This is something i can do quite easily with a single element since any ContentControl can have it's verticalContentAlignment property set but then you only have a single child element to play with and i'm back to square one.

Any help would be massively appreciated.

+2  A: 

Fixed it as i asked it!

What i needed to do was place a StackPanel inside a ContentControl and set the StackPanels VerticalAlignment to Center. Seems obvious now!

Stimul8d
Just as aside, if you don't already use it then KaXaml is a brilliant tool for fixing little things like this.. much faster than a change/recompile in Visual Studio/Blend :-)
Steven Robbins
+2  A: 
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid VerticalAlignment="Center">
     <StackPanel HorizontalAlignment="Center">
      <TextBlock>First</TextBlock>
      <TextBlock>and the second</TextBlock>
     </StackPanel>
    </Grid>
</Window>

You could also write your own Panel subclass that does this automatically.

HTH, Kent

Kent Boogaart
Actually, you don't need the wrapping grid. Just set both the HorizontalAlignment and VerticalAlignment properties on the StackPanel itself and you're good to go.
MarqueIV