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 に答える