How to Measure the size of a string, before it really existing on some TextBox, in Windows Store App RRS feed

  • Question

  • Hi Geeks,

    I meet a text measuring problem under Windows Store App.

    I wanna get the bounds of a string, before it set to a TextBox, but there is no text measuring APIs in Windows Store App.

    Someone try to measure text by TextBlock, but I found the width has a measurement error for some special string such as "FAFAFAFAFA". Seems the TextBlock will have different rendering logic from it in TextBox.

    I also try to create another new TextBox for measurement, but it seems not works.

            public static Size MeasureText(string text, TextBox textContainer)
                TextBox textBox = new TextBox()
                    FontFamily = textContainer.FontFamily,
                    FontSize = textContainer.FontSize,
                    FontStretch = textContainer.FontStretch,
                    FontStyle = textContainer.FontStyle,
                    FontWeight = textContainer.FontWeight,
                    Text = text,
                    TextWrapping= TextWrapping.NoWrap
                textBox.Measure(new Size(double.MaxValue, double.MaxValue));
                textBox.Arrange(new Rect(0.0, 0.0, 100, 100));
                if (string.IsNullOrEmpty(text))
                    return new Size();
                Rect start = textBox.GetRectFromCharacterIndex(0, false);
                Rect end = textBox.GetRectFromCharacterIndex(text.Length - 1, true);
                return new Size(end.Right - start.Left, start.Height);

    Anyone have any idea about this question?

    Thanks in advance.

    Wednesday, June 5, 2013 3:23 AM