Get height of TextBlock in WPF

Sometimes it's quite nice to get the height of a textblock at the same time it's created. In WPF however there's a couple of events that handle the layout functions when an element is rendered, and before these have been fired, you won't get proper values from the DesiredSize property. The good news is that these can be triggered by the Arrange function. You call the Arrange function with a Rect (rectangle) representing the column width and max height (example below use 1000px, but you might need more for longer texts) of your text.

TextBlock t = new TextBlock();
int columnWidth = 310;
t.FontFamily = new FontFamily("Arial");
t.FontSize = 20;
t.Text = "Here goes the text..";
t.Width = columnWidth;
t.TextWrapping = TextWrapping.Wrap;
t.Arrange(new Rect(0,0,columnWidth,1000));
int textHeight = (int)t.DesiredSize.Height;

Related posts:

Comments

comments powered by Disqus