[ACCEPTED]-How can I vertically align a TextBox inside a StackPanel?-stackpanel

Accepted answer
Score: 18

A stackpanel, no matter how you stretch 8 it, will collapse around the children. you 7 can't make it grow more than that. Basically, that 6 "Height=700" is not helping you.

So either 5 set VerticalAlignment on the StackPanel 4 to "center" so that the stackpanel goes 3 into the center of the dockpanel...or remove 2 the stackpanel altogether and set VerticalAlignment="Center" on 1 the TextBlock.

Score: 11

Seems I asked this question 10 months ago, I got the above scenario to work 1 by replacing the StackPanel with DockPanel LastChildFill=True like this:

<DockPanel LastChildFill="True">
    <TextBlock
        DockPanel.Dock="Top"
        Text="Test"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        FontSize="200" x:Name="TheNumber"/>
</DockPanel>
Score: 5

I stumbled across this which seems to work 9 perfectly:

<Grid>
    <TextBlock Text="My Centered Text"
               TextAlignment="Center" 
               VerticalAlignment="Center"/>
</Grid>

The Grid ensures that the single 8 TextBox within it fills the solitary cell 7 in the grid and the VerticalAlignment in 6 the TextBlock ensures that the text is centered 5 within than.

Simply position/align your text 4 horizontally however you require (the above 3 snippet centers it in this axis also, but 2 changing this doesn't alter the vertical 1 centering).

More Related questions