Tuesday, February 15, 2011

WPF: Textblock vertical alignment with given height

I was needed to set the alignment of textblock in center and also need to set height which is greater than normal textblock text height. But problem is when the text height is assigned then vertical alignment of textblock does not work. To solve this problem easy way to set padding so that the textblock text remain at center position. For that you need to measure the height of textblock before setting the custom height of textblock. After getting the desiredsize of textblock you can calculate the top padding of text in textblock. Then set the padding and custom height of textblock. This will solve the problem of making text position at center giving custom height.
textBlock.Measure(new Size(infiniteWidth, infiniteHeight));
var textBlockHeight = textBlock.DesiredSize.Height;
var textBlockTopPaddig = (CustomHeight - textBlockHeight)/2;
textBlock.Padding = new Thickness(0,textBlockTopPaddig,0,0);
textBlock.Height = CustomHeight;
 
XAML 
But if you want to set the custom height of TextBox from XAML then create a StackPanel and set the TextBlock inside that StackPanel. Instead of setting TextBlock height set the height of StackPanel and set StackPanel vertical alignment as VerticalAlignment.Center. So now textblock will be displayed in center of StackPanel. 

No comments:

Post a Comment