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

╄→гoц情女王★ 提交于 2019-12-01 02:45:09

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.

xJonx

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.

I appreciate that this is a rather old question, but I have found that using the following code

        TextBlock textBlock = new TextBlock();
        textBlock.Text = "NR valve";
        Size msrSize = new Size(100, 200);
        textBlock.Measure(msrSize);
        Size dsrdSize = textBlock.DesiredSize;

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.

public static Size ShapeMeasure(TextBlock tb) {
    // Measured Size is bounded to be less than maxSize
    Size maxSize = new Size(
         double.PositiveInfinity, 
         double.PositiveInfinity);
    tb.Measure(maxSize);
    return tb.DesiredSize;
}

public static Testit() 
{
    TextBlock textBlock = new TextBlock();
    textBlock.Text = "NR valve";

    Size text size = ShapeMeasure(textBlock);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!