Silverlight Tip of the Day #58 – Text Wrapping and Line Breaks in TextBlocks
TextBlocks are a great control to use in Silverlight to display read only text. In Tip of the Day #45 I covered the basic usage of TextBlocks including formatting and text runs.
For this tip I would like to show you how to make a TextBlock with wrapping text and line breaks.
To make a TextBlock wrap its text you will need to set TextWrapping ="Wrap" on the TextBlock. The following example below shows a TextBlock in a ContentControl that is only 100 pixels wide. With TextWrapping set to “Wrap”, the TextBlock will wrap to a new line each time its contents reach 100 pixels in width.
XAML:
<Canvas Margin="10">
<ContentControl Width="100">
<TextBlock TextWrapping="Wrap">
A lie can travel half way around the world while the truth is putting on its shoes.
--Mark Twain
</TextBlock>
</ContentControl>
</Canvas>
Result with TextWrapping = “Wrap”:
Without TextWrapping:
As you may notice the text above does not include any of the line breaks seen in the XAML. To insert a line break all you need to do is insert a <LineBreak> tag within the text.
Example:
<Canvas Margin="10">
<ContentControl Width="100">
<TextBlock TextWrapping="Wrap">
A lie can travel half way around the world while the truth is putting on its shoes.
<LineBreak></LineBreak>
<LineBreak></LineBreak>
--Mark Twain
</TextBlock>
</ContentControl>
</Canvas>
Result:
Thank you,
--Mike Snow
Subscribe in a reader