2

I have failed to find a Windows Runtime equivalent to the following WPF code to measure the width of a string:

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

Does anybody know if it can be done in Metro?

Athari
  • 33,702
  • 16
  • 105
  • 146
Ludvig A. Norin
  • 5,115
  • 7
  • 30
  • 34
  • 1
    how about displaying it with opacity 0 and get the with?(just a proposition as a workaround if there is no API at the moment) – Lukasz Madon Feb 03 '12 at 21:13
  • 1
    Thanks lukas, you've pointed me in the right direction. However, you don't need to add the control to the visual tree in order to measure it, see my answer below. I have doubts as to wether this is a working solution given all circumstances, though. – Ludvig A. Norin Feb 04 '12 at 10:21

2 Answers2

5

It is possible, I've found one method that gives useful measurements, but I am not sure it is the best way of doing it:

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

My gut feeling is that there are situations in which this code will give an unexpected result.

Ludvig A. Norin
  • 5,115
  • 7
  • 30
  • 34
  • This method doesn't include trailing whitespace as the example code above does. Any idea on how to force it to include that (without using non-breaking space since that is a different size)? – borrrden Apr 09 '13 at 04:42
  • @borrrden - for reference the only thing I've been able to do about that is to measure the string after appending a known bit of text to it, and then subtracting the length of that known text after the measurement is done. – Mike Goatly Jun 30 '14 at 21:15
2

Try this:

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