1

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.

Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • With 'measuring' you mean detect the number of characters in a multi-line textblock? – A. Wolf Oct 17 '18 at 12:28
  • I've updated my question to clarify. – Sheridan Oct 17 '18 at 13:41
  • If you use TextBlock or Label you can use the .ActualHeight property, also you can set MinHeight as the single line height and compare in code behind or divide by this value to find how many lines, TextBlock will work better because you have additional text format options such as line height etc – Mr. Noob Oct 19 '18 at 14:16
  • As I mentioned in my question, _I need to measure the strings in a non UI based project, where UI DLLs are not welcome_. But thanks for your response. – Sheridan Oct 24 '18 at 10:24

1 Answers1

1

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.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Thank you Clemens. What would we do without you here? ;) However, this code still doesn't seem to measure the strings accurately. I have had to increase the font size value used to get better results, but still, some strings are measured very poorly. Are you aware of any other ways to measure text in a WPF application? – Sheridan Oct 17 '18 at 15:06
  • No sorry, this is the only WPF method I'm aware of. – Clemens Oct 17 '18 at 15:08
  • Thanks again Clemens. – Sheridan Oct 17 '18 at 16:15