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?
I think it should be sufficient to call the
UIElement.Measure(Size)
method and subsequently check theUIElement.DesiredSize
property. For more information, check the provided MSDN links.I appreciate that this is a rather old question, but I have found that using the following code
dsrdSize is returned as {47.05,15.96}. The trick seems to be making the msrSize larger than the expected actual size. msrSize seems to act as a limit for the DesiredSize() result. For example, using msrSize = new Size(10, 10), results in a dsrdSize of {10,10} here. Hope this helps someone.
The call to
UIElement.Measure(Size)
, takes as a parameterSize
. The second callUIElement.DesiredSize
returns whateverSize
you passed into theMeasure
method.I think this is the case because
UIElement
(TextBlock
in this case) is NOT a child of any control (yet) and thereforeDesiredSize
has no reason to be anything different.