17

在 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 };
}

除了调用服务器之外,Silverlight 中是否有一种以像素为单位获取宽度的好方法(目前高度并不重要)?

4

1 回答 1

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;
}

这是一个黑客,毫无疑问。

于 2011-02-04T16:34:45.300 回答