如何计算Metro中字符串的宽度(不显示)?

时间:2012-02-03 09:04:26

标签: c# windows-8 windows-runtime microsoft-metro

我找不到与以下WPF代码等效的Windows运行时来测量字符串的宽度:

FormattedText formattedText = new FormattedText(in_string,in_culture,in_flowdir,in_font,in_sz,in_color);
string_width = formattedText.WidthIncludingTrailingWhitespace);

有人知道是否可以在Metro中完成吗?

2 个答案:

答案 0 :(得分:5)

有可能,我发现了一种可以提供有用测量的方法,但我不确定这是最好的方法:

// Setup the TextBlock with *everything* that affects how it 
// will be drawn (this is not a complete example)
TextBlock^ tb = ref new TextBlock; 
tb->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Top; 
tb->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Left; 
tb->Height = in_height; 
tb->Text = text;

// Be sure to tell Measure() the correct dimensions that the TextBox 
// have to draw in!
tb->Measure(SizeHelper::FromDimensions(Parent->Width,Parent->Height)); 
text_width = tb->DesiredSize.Width;

我的直觉是,在某些情况下,此代码会产生意外结果。

答案 1 :(得分:2)

试试这个:

private double stringWidth(string s, double fontSize)
    {
        if(s==" ")
            s = "\u00A0";  //this line wasn't required in silverlight but is now

        TextBlock t = new TextBlock()
        {
            FontSize = fontSize,
            Text = s
        };
        t.Measure(new Size(double.MaxValue, double.MaxValue));  //this line wasn't required in silverlight but is now
        return t.ActualWidth;
    }