1

We are trying to measure the width of text, as displayed (not the number of characters).

In Winforms there is a method called Grapihcs.MeasureCharacterRanges. In WPF, the FormattedText.WidthIncludingTrailingWhitespace. While it would seem these would give the same value, they don't. Why not? For us Graphics.MeasurecharacterRanges, but we can't really pullin winforms, just for one method. It is a WPF app.

jeff
  • 3,269
  • 3
  • 28
  • 45
  • Maybe your monitor has a higher resolution than 96dpi ? WPF is resolution independent, but `Graphics` aren't, this could explain the difference. As I am not sure about that, I just leave this as a comment and not an answer. – Luke Marlin May 02 '13 at 16:09
  • Maybe this might help? http://stackoverflow.com/questions/632445/measuring-text-in-wpf – Matthew Layton May 02 '13 at 16:24

2 Answers2

3

We are using the following utility class to perform simple text measurements in WPF:

public static class TextUtilities
{
    public static Size MeasureText(string text,
        FontFamily family, double size, FontStyle style, FontWeight weight, FontStretch stretch, TextFormattingMode formattingMode)
    {
        FormattedText formattedText = new FormattedText(
            text,
            CultureInfo.CurrentCulture,
            FlowDirection.LeftToRight,
            new Typeface(family, style, weight, stretch),
            size,
            Brushes.Black,
            null,
            formattingMode);

        return new Size(formattedText.Width, formattedText.Height);
    }

    public static Size MeasureText(string text, TextBlock textBlock)
    {
        return MeasureText(text,
                    textBlock.FontFamily,
                    textBlock.FontSize,
                    textBlock.FontStyle,
                    textBlock.FontWeight,
                    textBlock.FontStretch,
                    TextOptions.GetTextFormattingMode(textBlock));
    }


    public static Size MeasureText(string text, Control control)
    {
        return MeasureText(text, control.FontFamily, control.FontSize,
            control.FontStyle, control.FontWeight, control.FontStretch,
            TextOptions.GetTextFormattingMode(control));
    }
}
0

WPF uses a device-independent unit for most measurements of graphics elements, and it's likely different than the units used for WinForms. See this link on MSDN regarding the Height property of FrameworkElements, and the units used.

Steve
  • 6,334
  • 4
  • 39
  • 67