Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolutely centered content inside a WPF layout panel

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.

like image 367
EightyOne Unite Avatar asked Feb 23 '09 11:02

EightyOne Unite


2 Answers

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

like image 105
Kent Boogaart Avatar answered Oct 08 '22 16:10

Kent Boogaart


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!

like image 28
EightyOne Unite Avatar answered Oct 08 '22 15:10

EightyOne Unite