Search code examples
xamlwindows-store-apps

Windows Store Apps: measure many pixels a TextBlock width will be?


Is there a way to measure many pixels will a TextBlock width will occupy? let's say I have a string with length of 10 characters.

and I have a text block (without an assigned width value), I'll set the string to the Text property of that textblock.

Is there a way to measure the actual width of the textblock before adding it to the layout?


Solution

  • Well, the only way I got is to create a new -in memory- text block- then assign it the same text, style and attributes as my target TextBlock, I assumed that my text block has a fixed height, to calculate it's desired width to fit the text, I made the following function:

    private double CalculateDesiredWidth(string text, TextBlock targetText)
            {
                int MIN_TEXT_WIDTH=200;
                //create a new text block to calculate how much space will the string occupy
                TextBlock txt = new TextBlock();
                txt.Text = text;
                txt.FontSize = 16;
                txt.Margin = targetText.Margin;
                Size desiredSize = new Size(0, targetText.ActualHeight);
                Rect desiredRect = new Rect(new Point(0, 0), desiredSize);
    
                //measure the desired size
                txt.Measure(desiredSize);
                txt.Arrange(desiredRect);
                //if the desired width is small, use the minimum default width
                if (txt.ActualWidth <= MIN_TEXT_WIDTH)
                    return MIN_TEXT_WIDTH;
                //calculate the desired area
                double desiredArea = txt.ActualWidth * txt.ActualHeight;
                //calculate the the width required to fit the desired area to my text box
                double width = desiredArea / (targetText.Height - txt.Margin.Top - txt.Margin.Bottom);
                return width;
            }