Search code examples
c#wpftextformattingformatted-text

FormattedText Width property does not take trailing spaces into account


I am using System.Windows.Media.FormattedText to do some low level rendering (specifically, trying to render math equations in a typographically pleasing manner). For this, precise metrics on the text blocks I am using are critical.

I am creating several FormattedText objects and using these at the lowest level of rendering. The problem is that if any of these contain trailing spaces, that space is not taken into account when computing the FormattedText.Width property. For example, if I write:

double w1 = new FormattedText ("Hello", ...).Width;
double w2 = new FormattedText ("Hello    ", ...).Width;

w1 and w2 turn out to be the same. Leading spaces are measured correctly. How do I force FormattedText to measure these trailing spaces as well?


Solution

  • Change from using the Width property to using the WidthIncludingTrailingWhitespace property.

    double w1 = new FormattedText ("Hello", ...).WidthIncludingTrailingWhitespace;
    double w2 = new FormattedText ("Hello    ", ...).WidthIncludingTrailingWhitespace;
    

    With this code you should see two different width values.