问题
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.
回答1:
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>
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)
回答2:
I had the same issue where I had a lot of buttons where I needed a ViewBox to be able to handle localization. The reason for this is that Width is set to Infinity, because the button or control width is determined by the parent control. Fortunately, controls have a property the is called ActualWidth. This property holds a rendered width and I can use this in a binding:
<Button>
<Button.Content>
<Viewbox StretchDirection="DownOnly">
<TextBlock Width="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Button}}" TextWrapping="Wrap" TextAlignment="Center" Text="{Binding }" />
</Viewbox>
</Button.Content>
</Button>
So the textblock gets the width the Button button currently have. If the button changes width, it is automatically updated. The Textblock will wrap according to the width given and viewbox will only shink when nessesary (providing StretchDirection="DownOnly" is applied).
https://docs.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.actualwidth?view=netframework-4.8
来源:https://stackoverflow.com/questions/17717999/textblock-text-doesnt-wrap-when-placed-inside-a-viewbox