0

I am doing this in c# on Windows phone. I want a TextBlock vertically center aligned in a StackPanel with height of 58. Here is what I did:

<StackPanel Height="58" VerticalAlignment="Center">
                <TextBlock Text="{Binding Name}" Style="{StaticResource SubheaderTextBlockStyle}" Foreground="black"  />
            </StackPanel>

But it does not vertically center aligned. Can you please tell me why and how can I fix this?

Thank you.

Kulasangar
  • 9,046
  • 5
  • 51
  • 82
michael
  • 106,540
  • 116
  • 246
  • 346
  • Check this post. StackPanel is probably a wrong option in your case.http://stackoverflow.com/questions/1918847/how-can-i-vertically-align-a-textbox-inside-a-stackpanel – Krishna Veeramachaneni Oct 15 '14 at 06:22

3 Answers3

2

I guess you should go with the Grid than StackPanel as @The-First-Tiger & @Krishna mentioned above and also have you misplaced the VerticalAlignment? You wanted the TextBlock to align vertically center, so it should be like this:

 <Grid Height="58" >
   <TextBlock  VerticalAlignment="Center" Text="{Binding Name}"  Foreground="black"  />
 </Grid   
Kulasangar
  • 9,046
  • 5
  • 51
  • 82
  • Thanks. I am new to C# Windows programming. Is Grid more heavy than StackPanel? meaning does it use more memory? In general, should I use StackPanel instead of grid if I can? – michael Oct 15 '14 at 16:14
  • @michael As I'm not clear with the memory consumption of each of them would suggest to have a look at this. http://stackoverflow.com/questions/15575854/grid-and-stackpanel-which-has-the-better-performance – Kulasangar Oct 15 '14 at 16:21
0

StackPanel is not for this. It 'stacks' things not aligns them.

Try using a Grid instead:

<Grid Height="58">
    <TextBlock Text="{Binding Name}" Height="20" Foreground="black"/>
</Grid>
The-First-Tiger
  • 1,574
  • 11
  • 18
0

According to MSDN docs about StackPanel

A StackPanel Arranges child elements into a single line that can be oriented horizontally or vertically.

So in your case, StackPanel is not the right control to use. If you want your control to be fixed at a particular position, you can use DockPanel and place your control inside it. Children Controls of DockPanel can use the .Dock property to align themselves

<DockPanel>
        <Button DockPanel.Dock="Bottom" Name="btn"  HorizontalAlignment="Center" 
                VerticalAlignment="Bottom"></Button>
</DockPanel>
sohaiby
  • 1,168
  • 3
  • 24
  • 39