TextBlock text doesn't wrap when placed inside a ViewBox

Sun picture Sun · Jul 18, 2013 · Viewed 9.2k times · Source

I have a TextBlock with a long line of text which I want to wrap. I've placed the TextBlock within a ViewBox expecting the text size to change while still wrapping, however this doesn't seem to happen. The ViewBox just resizes the TextBox so that all the text fits on one line making the text really small.

How can I use the ViewBox to resize the text while still using TextWrapping.

Here is my code:

<Viewbox>
    <TextBlock Text="The Option text can also dynamically grow/shrink to fit more content. More text to go here....................." TextWrapping="Wrap"/>
</Viewbox>

This is part of a Windows 8 store application so is WinRT Xaml.

Answer

Luke Puplett picture Luke Puplett · Jul 18, 2013

Just set a width on the TextBlock.

        <Viewbox Width="500">
            <TextBlock Width="100" TextWrapping="Wrap">This is the text that's long and on two lines.</TextBlock>
        </Viewbox>

TextBlock with width 100 in ViewBox with width 500

So the ViewBox will zoom in/out its entire contents. If you don't restrict its contents by either setting a width on the TextBlock, the ViewBox will give it infinite space to expand into. You can also add a root Grid with a width and height within the ViewBox and lay your elements out in that, then the whole lot will get zoomed according to the width of the ViewBox.

In the image, the width of the TextBlock 100 is zoomed to be the width of the ViewBox which is 500. So to get the wrapping you want, just tweak the TextBlock width until it looks nice.

(Obviously it should say three lines but I'm not re-uploading just for that)