MeasureString for Silverlight

I was working on an annotation tool for an application I am developing using the Esri Silverlight API. The TextSymbol class has properties to specify the X and Y offsets in order to position the text relative to the symbol’s base point. I needed to calculate the size of the string in order to determine the offset I wanted to use. Silverlight seems to have no intrinsic equivalent to the MeasureString function so I hacked this up.

I built it as an extension method to the System.String class. The Font class is just a simple container that I use as a parameter. It uses a TextBlock to do the work, which strikes me as a little hackish, but it seemed to be the most direct way to do things. I hope it saves others a little work. Enjoy.

[sourcecode language=”csharp”]
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Helpers
{
//Simple container class for font properties
public class Font
{
public FontFamily Family { get; set; }
public FontStyle Style { get; set; }
public FontWeight Weight { get; set; }
public double Size { get; set; }
}

public static class Extensions
{
//Extension method on System.String
public static Size Measure(this String str, Font font)
{
Size retval = new Size();
try
{
TextBlock l = new TextBlock();
l.FontFamily = font.Family;
l.FontSize = font.Size;
l.FontStyle = font.Style;
l.FontWeight = font.Weight;
l.Text = str;
retval.Height = l.ActualHeight;
retval.Width = l.ActualWidth;
}
catch
{
retval.Height = 0;
retval.Width = 0;
}
return retval;
}
}
}
[/sourcecode]