Question from the Silverlight forums: Limiting TextBlock text rendering to a specific region

Question:

I've got this XAML code in my application:

<Canvas Height="25" Width="75" Canvas.Top="250" Canvas.Left="250" Background="LightGray">

    <TextBlock Width="75" FontSize="12" Text="This is a long line"></TextBlock>

</Canvas>

Problem is eventually the text goes beyond border of canvas. Ideally I want text string be cut right by canvas border.

I though about using text wrapping. But the TextBlock would wrap the text and continue on next line which is outside of canvas as well.

image

Does anyone know how to do that with Silverlight?

 

Answer:

If you need an absolute border on a TextBlock just add a Clipping region around it.
The primitive way is setting the "Clip" property to the path of the region you'd like to border the TextBlock with.
The clipping region just "removes" all rendering the belongs to that element that is outside the region.

image

 

However, The more "blendy" way of doing that is drawing the shape you want to border the TextBlock and position it as a border.

image


Make sure the border is selected.

 image

Select the TextBlock (using Ctrl + select) so both the TextBlock and region are selected.

image

Through the file menu select "object --> path --> make clipping path".

image 

And that will automatically create populate the Clip path with the region you've drawn.

image 

 

Let's add some more text into our TextBlock so we could see the text wrapping being cut.

image

    <TextBlock Width="184" Height="64" Canvas.Left="80" Canvas.Top="77" Text="Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. Hello world. " TextWrapping="Wrap" Clip="M0.5,0.5 L143.5,0.5 L143.5,48.5 L0.5,48.5 z"/>

And in our browser we'll see our TextBlock has a hard-border around it and no text can be rendered outside of it:

image

 

We can also use the Clip property in order to place a definitive border on many other elements, like the Root canvas of a page.

 

Link: http://silverlight.net/forums/p/5976/18338.aspx

Published Tuesday, November 20, 2007 12:19 PM by Justin-Josef Angel [MVP]

Comments

No Comments