0

How to force TexBlock and RichTextBlock to change FontSize so that the text fits in the window. When changing the text, if the text is too large, then it does not fit in the window. How to make it fit completely?

viewBox is not suitable because "TextWrapping=Wrap" does not work in it

Update: I have a TextBlock for the entire width and height of the window. The user can change the text of any length. I would like to force TextBlock to change FontSize so that all the text fits in the window. viewBox is not suitable because "TextWrapping=Wrap" does not work in it.

I wrote a temporary code. But it's a terrible code. I would like to find a more correct code:

        var textBlockHeight = Convert.ToInt32(page.ActualHeight - textBlock.Margin.Bottom);
        var textBlockWidth = Convert.ToInt32(page.ActualWidth - (textBlock.Margin.Right * 2));

        var canvas = new CanvasTextFormat
        {
            FontSize = 150,
            WordWrapping = CanvasWordWrapping.Wrap,
        };

        var device = CanvasDevice.GetSharedDevice();
        var layout = new CanvasTextLayout(device, text, canvas, textBlockWidth, 0);
        var textHeight = (int)layout.DrawBounds.Height;


        while (textBlockHeight < textHeight)
        {
            layout = new CanvasTextLayout(device, text, canvas, textBlockWidth, 0);
            textHeight = (int)layout.DrawBounds.Height;

            canvas.FontSize--;

            if (canvas.FontSize <= 3)
            {
                break;
            }
        }

        textBlock.FontSize = canvas.FontSize;
        textBlock.Text = text;
Яша
  • 3
  • 2
  • 2
    Please provide enough code so others can better understand or reproduce the problem. – Community Apr 08 '22 at 16:43
  • If you want Dynamic, you will need to use Adaptive Triggers with a DataTemplate. The video attached demonstrates this nicely. https://www.youtube.com/watch?v=ksliZGMMj8k – Shawn Ramirez Apr 08 '22 at 19:32
  • Could you please share more details about your requirements? Do you have a specific scenario so that we could understand better what you want to get? – Roy Li - MSFT Apr 11 '22 at 02:18

0 Answers0