Search code examples
wpftextblockmeasure

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


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?


Solution

  • 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.