Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 382
Scott Whitlock Avatar asked Jun 07 '10 10:06

Scott Whitlock


2 Answers

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.

like image 74
gehho Avatar answered Oct 26 '22 22:10

gehho


The call to UIElement.Measure(Size), takes as a parameter Size. The second call UIElement.DesiredSize returns whatever Size you passed into the Measure method.

I think this is the case because UIElement (TextBlock in this case) is NOT a child of any control (yet) and therefore DesiredSize has no reason to be anything different.

like image 43
xJonx Avatar answered Oct 27 '22 00:10

xJonx