Search code examples
wpfstringmultilinemeasure

How to measure multi-line text in WPF?


The title really says it all... I need to know how to measure multi-line text in WPF. I really can't believe that this question hasn't already been asked here.

I have found solutions for measuring single line text in WPF (WPF equivalent to TextRenderer), or multi-line text in Windows Forms (C# – Measure String Width & Height (in pixels) Including Multi-line Text), but not multi-line text in WPF. I cannot use the Windows Forms DLL, because I need to measure the strings in a non UI based project, where UI DLLs are not welcome.

To clarify further, what I need is a method, like the Graphics.MeasureString method, that I can pass a set width into, that will return the height in pixels required to render the string in the UI... that can be used without using UI related DLLs.


Solution

  • You may create a FormattedText instance and set its MaxTextWidth property, which makes the text wrap. Then either get the Bounds of its geometry, or perhaps only its height from the Extent property:

    var testString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor";
    
    var formattedText = new FormattedText(
        testString,
        CultureInfo.InvariantCulture,
        FlowDirection.LeftToRight,
        new Typeface("Segoe UI"),
        20,
        Brushes.Black);
    
    formattedText.MaxTextWidth = 200;
    
    var bounds = formattedText.BuildGeometry(new Point(0, 0)).Bounds;
    var height = formattedText.Extent;
    

    Not sure however why height and bounds.Height are not exactly equal.