以编程方式为Silverlight测量以像素为单位的文本字符串

Ali*_*ned 17 text silverlight-4.0 fontmetrics

在WPF中,System.Windows.Media命名空间MSDN FormattedText中有FormattedText,我可以这样使用:

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 };
}
Run Code Online (Sandbox Code Playgroud)

除了调用服务器之外,在Silverlight中是否有一个很好的方法来获得像素宽度(此时高度并不重要)?

Ken*_*ith 30

我见过的一种方法,可能在你的特定实例中不起作用,就是将文本抛出到一个没有样式的TextBlock中,然后获得该控件的宽度,如下所示:

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

毫无疑问,这是一个黑客攻击.