How do I measure the size of a TextBlock in WPF before it is rendered?

Scott Whitlock picture Scott Whitlock · Jun 7, 2010 · Viewed 12.2k times · Source

I have a WPF DataTemplate with two TextBlock controls (stacked) and then some other elements underneath. Due to some complicated layout code, I need to know the height of the two TextBlock elements so that I can draw some fancy connector lines, and line up other controls, etc.

If I know the text that's going into the TextBlocks, and I know the font, etc., is there some way I can compute or measure the height of these TextBlocks without actually rendering them?

Answer

gehho picture gehho · Jun 7, 2010

I think it should be sufficient to call the UIElement.Measure(Size) method and subsequently check the UIElement.DesiredSize property. For more information, check the provided MSDN links.