7

I'm trying to vertically center the content of a TextBox with the VerticalContentAlignment property but it seems to have no effect at all. The text stays at the top. Can anyone tell me how to do this?

Here's my code:

<TextBox Grid.Column="1"
     Grid.Row="0"
     Width="200"
     Height="28"
     VerticalAlignment="Center"
     VerticalContentAlignment="Center" />
Anonymous Coward
  • 856
  • 1
  • 11
  • 27

2 Answers2

7

It is possible to make the TextBox center its text vertically. However, that does require you to reapply its ControlTemplate.

To do this:

  1. Copy the Style and the ControlTemplate from the TextBox Styles and Templates page on MSDN to a suitable <UserControl.Resources> element. (This ControlTemplate is actually for a validation tooltip; the ControlTemplate we'll change is within the Style.)
  2. Find the ScrollViewer element within the Style for the TextBox, and add a VerticalAlignment="Center" property to it.

Alternatively, you could add the property

VerticalAlignment="{TemplateBinding VerticalContentAlignment}"

to the ScrollViewer. This should allow you to set the vertical alignment of the contents of your TextBoxes using the VerticalContentAlignment property.

You can follow much the same approach if you wish to change the horizontal alignment of a TextBox's content as well.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
-1

The XAML code is correct, the following should be sufficient:

<TextBlock Text="Centered Text" VerticalAlignment="Center" />

Can you try that code outside your grid?

Check the attributes you defined on your Grid, this will probably cause the behaviour you have. Can you post the complete XAML code?

emp
  • 4,926
  • 2
  • 38
  • 50
  • Since your code produces a TextBlock which has exactly the size of the text it contains the text will be centered. However, if I use a _TextBox_ and set the Height to 30 the problem is still there. – Anonymous Coward Jul 20 '11 at 09:13