Clipping in Silverlight

This is something I found frustrating in Silverlight. The problem I ran into is that the instructions I found in the Expression Blend User Guide don't work.

The good news is it is fairly straight forward to add a clipping region by editing the XAML directly in Visual Studio. I prefer editing the XAML in Visual Studio because IntelliSense works, making life much easier. To add clipping to a canvas use the following code:

<Canvas x:Name="Bio" Canvas.Left="435" Canvas.Top="133" Width="400" Height="300">
  <Canvas.Clip>
    <RectangleGeometry Rect="0, 0, 400, 300"/>
  </Canvas.Clip>

  <TextBlock Width="384" Height="54" Canvas.Left="16" Canvas.Top="8" Text="Session Title" x:Name="txtBio"/>
</Canvas>

This will allow you to assign any amount of text in the textblock and it will not spill past the edges of the canvas container.

As you have probably already guessed you can apply this clipping code to almost any object including rectangles and textblocks. In fact you could have shortened the above XAML by applying the clipping region to the textblock itself like so:

<TextBlock Width="384" Height="54" Canvas.Left="16" Canvas.Top="8" Text="Session Title" x:Name="txtBio">
  <TextBlock.Clip>
    <RectangleGeometry Rect="0, 0, 400, 300"/>
  </TextBlock.Clip>
</TextBlock>

Also if you look at the options in intellisense you can create clipping regions based on rectangle, ellipse, line, and path geometries. For now the rectangle seems to be enough for 99% of what I would want to do.

Currently rated 3.2 by 6 people

  • Currently 3.166667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: Tim Miller
Posted on: 2/20/2008 at 4:31 PM
Tags: , ,
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Related posts

Comments

Jeff Z us

Tuesday, September 09, 2008 12:38 PM

Jeff Z

Any thoughts on the easiest way to add an ellipses to the text that gets clipped?

For instance, if my rectangle clipped the above sentence it would look like:

Any thoughts on . . .

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Wednesday, January 07, 2009 3:56 AM