How to fit large text within the application’s border using XAML and C# in UWP.


In this post, I’m going to show you how to make sure that your text will stay within borders of your applications and have a properly working ScrollViewer at the same time.

There are scenarios where we would like to have a TextBlock or RichTextBlock on a page. Sometimes sentences are pretty small and could fit within the bounds and there is no need to have a ScrollViewer. But there are also cases when a sentence could go after another or a single sentence could be too large to fit.

First, let’s see what’s going to happen if we simply put both RichTextBlock and TextBlock without any changes within a ScrollViewer. For this example, I’m going to use Lorem Ipsum Dolor sample text:

And here’s the result of this code:

From these two screenshots, we can clearly see that when we change the size of the window, text can’t fit correctly within bounds of the application and goes beyond them. Why is this happening? There are two aspects of this issue:

  • The container which holds RichTextBlock and TextBlock (in this case StackPanel) has no width and therefore both text controls have the widths of their text strings.
  • TextBlock and RichTextBlock should have TextWrapping parameter set to “WrapWholeWords” or “Wrap” so that it could fit within bounds.

If we “fix” these by setting the width of StackPanel to for instance to “500” and set TextWrapping for both text controls we’ll receive next result:

After made changes, the text fits within the bounds and if the height will be changed, the ScrollViewer will be working as it should. But now the problem is that the width of StackPanel is static and if the window’s width will be bigger or smaller than “500”, the text won’t be following new sizes. The solution, which I found is to track the event when the size is changed and take current bounds and set the StackPanel’s width to the bounds’ one.

In code, it looks like this:
XAML:

C#:

The result of these changes:

As you can see now, it doesn’t matter what’s the width and length of the application’s window, the text will always be stretched within the bounds and at the same time, ScrollViewer will be working as it should.

GitHub project’s repo: https://github.com/svbutko/LargeTextAndScrollViewer

You may also like...