Programmatically measure text string in pixels for Silverlight

AlignedDev picture AlignedDev · Feb 4, 2011 · Viewed 7.6k times · Source

In WPF there is the FormattedText in the System.Windows.Media namespace MSDN FormattedText that I can use like so:

private static Size GetTextSize(string txt, string font, int size, bool isBold)
{
   Typeface tf = new Typeface(new System.Windows.Media.FontFamily(font),
                             FontStyles.Normal,
                             (isBold) ? FontWeights.Bold : FontWeights.Normal,
                             FontStretches.Normal);
   FormattedText ft = new FormattedText(txt, new CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, tf, (double)size, System.Windows.Media.Brushes.Black, null, TextFormattingMode.Display);
   return new Size { Width = ft.WidthIncludingTrailingWhitespace, Height = ft.Height };
}

Is there a good approach in Silverlight to getting the width in pixels (at the moment height isn't important) besides making a call to the server?

Answer

Ken Smith picture Ken Smith · Feb 4, 2011

An approach that I've seen used, that may not work in your particular instance, is to throw the text into an unstyled TextBlock, and then get the width of that control, like so:

private double GetTextWidth(string text, int fontSize)
{
    TextBlock txtMeasure = new TextBlock();
    txtMeasure.FontSize = fontSize;
    txtMeasure.Text = text;
    double width = txtMeasure.ActualWidth;
    return width;
}

It's a hack, no doubt.