How to calculate WPF TextBlock width for its known font size and characters?

DmitryBoyko picture DmitryBoyko · Feb 13, 2012 · Viewed 67.8k times · Source

Let's say I have TextBlock with text "Some Text" and font size 10.0.

How I can calculate appropriate TextBlock width?

Answer

RandomEngy picture RandomEngy · Feb 13, 2012

Use the FormattedText class.

I made a helper function in my code:

private Size MeasureString(string candidate)
{
    var formattedText = new FormattedText(
        candidate,
        CultureInfo.CurrentCulture,
        FlowDirection.LeftToRight,
        new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
        this.textBlock.FontSize,
        Brushes.Black,
        new NumberSubstitution(),
        1);

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

It returns device-independent pixels that can be used in WPF layout.