TextTrimming TextBlock for Silverlight

image

A handy feature of WPF is the ability to tell TextBlock to truncate its text to ellipses if it runs out of room. You do this by setting the TextTrimming property on the TextBlock and voilah!, your text ends up looking “like this…” This is especially handy in databinding or localization scenarios where you don’t know what the text will be ahead of time (and so you can’t necessarily allocate space properly).

So far this property is missing from Silverlight (we’re looking at you Silverlight 4).

I’ve written work arounds a couple of times, but never been really happy with the results. The problem is that I’ve normally derived the new control from TextBlock. In doing this, I’ve had a hard time getting the TextBlock to lay out it’s text in time for me to re-measure it and adjust accordingly. Everything gets kind of messed up and I’m usually one layout pass ahead or behind.

I took a different approach this time and made the Control itself a ContentControl that hosts a TextBlock. It works much better. Now I can opportunistically change the text and then re-layout, all from within the MeasureOverride of the ContentControl. It’s pretty clean.

There’s plenty of room for improvement here. Specifically, I’m just shortening the text one character at a time. I’m pretty confident that could be improved. Also, I only have the equivalent of TextTrimming=”CharacterEllipses” and not TextTrimming=”WordEllipses” but that one should be pretty easy to add too.

You can get the source here, or try out the control here.

27 comments

Scott Barnes

03 aug 2009

 

I imagine a world where there are 20 more Robbies…all producing quality additions to Silverlight such as this.

You complete me Robbie..complete…me..

-
Scott Barnes
Rich Platforms Product Manager
#1 Fan of Robbie
Microsoft.

 

Stefan Olson

03 aug 2009

 

Thanks for that! It is possible that Silverlight 4 will have this particular problem fixed. It has been marked as resolved(fixed) on connect (https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=372910). However, that’s no guarantee something’s fixed. Connect issues get opened and closed all the time with no explanation and no indication if they’re going to be fixed, so you never really know…

…Stefan

 

Darren David

04 aug 2009

 

Nice moves, my man. The lack of TextTrimming in SL is one of my biggest peeves. Looking forward to trying it out.

 
 

[...] Cunningham and Robby Ingebretsen did a similar implementation. Both trimming the text during the measure/arrange [...]

 

Robby Ingebretsen

05 aug 2009

 

@Scott. Ultimately, completing you was the goal. Sweet! I guess I’m done… :)

@Stefan. That’s fantastic. I would love for this control to not matter.

@Darren. Maybe we’re even now because you’re port of the Penner equations to WPF has been a staple for me!

 

Paul Rohde

05 aug 2009

 

Interestingly, a few of my co-workers were experimenting with something similar over the past week or two and did something similar, but it would fail if it had to trim a block of text that was too large. Have you considered using a binary algorithm to figure out the length of the text as opposed to removing one character at a time?

 

Robby Ingebretsen

05 aug 2009

 

@Paul. Yeah, that sounds like a great approach. For me that means dusting off my old CS books. If anyone wants to take a stab at a binary search approach to this, then by all means do so!

 

Scott Varcoe

05 aug 2009

 

For some reason, Silverlight 2 has a limit on the number of layout passes per page. I think the limit is 250 (see Brad’s blog: http://team.interknowlogy.com/blogs/bradcunningham/archive/2009/07/03/texttrimming-in-silverlight-2.aspx ). That’s why a binary search is needed.

Kiener’s solution gets around the problem by using a second TextBlock that is never displayed and therefore no layout passes are used. You might be able to do something similar.

Thanks for the post!

 

Shawn Wildermuth

05 aug 2009

 

Any chance you’d contribute it to the SilverlightContrib project?

 
 

[...] In Silverlight, you always have to deal with various browser size and display something exactly the same across browser. The problem is especially important for text display. Somehow, if you only have a limted size for text display and the drawback is that some texts are cropped. Therefore, we might want to have a solution to display “…” when some texts need to be trim. Here comes to a solution. Original Post [...]

 

Robby Ingebretsen

11 aug 2009

 

@Shawn. of course! Please feel free to include this. I’ll send you email as well to make sure you see this.

 

Laila

13 aug 2009

 

Thank you so much! This saved me a looot of time!

 

Rajiv

20 aug 2009

 

Hi,
Can I pl have the code for your home page 3D space effect images in Silverlight 3? Thanks a lot. Rajiv

 

Flo

02 sep 2009

 

Hey, thanks!

I tweaked the ReduceText Method a bit, because i got an exception when the Text.Length is zero:

///
/// Reduces the text.
///
/// The text.
/// The reduced length text
protected virtual string ReduceText(string text)
{
if (text.Length > 0)
{
return text.Substring(0, text.Length – 1);
}
else
{
return String.Empty;
}
}

 
 

[...] Solution: Robby Ingebretsen at NerdPlusArt.com (and of Kaxaml fame) has a dynamic control that does just this.  http://blog.nerdplusart.com/archives/texttrimming-textblock-for-silverlight. [...]

 
 

[...] Solution: Robby Ingebretsen at NerdPlusArt.com (and of Kaxaml fame) has a dynamic control that does just this.  http://blog.nerdplusart.com/archives/texttrimming-textblock-for-silverlight. [...]

 
 

[...] que se habían hecho a mano. Dejo la dirección del blog por si a alguien le resulta de utilidad TextTrimming TextBlock for Silverlight . Dentro del código fuente describen los términos de licencia de su uso. Posted: Nov 19 2009, [...]

 
 

[...] que se habían hecho a mano. Dejo la dirección del blog por si a alguien le resulta de utilidad TextTrimming TextBlock for Silverlight . Dentro del código fuente describen los términos de licencia de su uso. Posted: 19/11/2009 19:09 [...]

 
 

[...] Before Silverlight 4 if you wanted to dynamically add ellipses (the commonly used … to show that the sentence continues), you have to invent your own implementation which usually involves creating your own control that wraps a text based control and then manipulate the text inside based on the size.  Similar to what Robby Ingebretsen had to do here. [...]

 

links for 2009-11-25

25 nov 2009

 

[...] TextTrimming TextBlock for Silverlight This should work in WPF too. (tags: ui wpf silverlight tips controls) [...]

 

Sally

14 dec 2009

 

I am relatively new to Silverlight, but I really need to use this control. The question that I had was, it is possible for me to embed ‘More’, in which case the entire text will be displayed, and ‘Less’ will display the TextTrimmimg TextBlock. With html, this is easy, but I was wondering how to do in Silverlight.

 

Jabba

02 mar 2010

 

Thanks man, works good other than the argument out of range exception as mentioned above.

 
 

[...] to get started, I came across an excellent TextTrimming TextBlock on Robby Ingebretsen’s site: http://blog.nerdplusart.com/archives/texttrimming-textblock-for-silverlight which I used as a basis, and so am releasing my control under the same MIT license that he used. I [...]

 

Ed

09 mar 2010

 

Hi Robbie,

Great post, and a very useful control. I used it as a basis for a similar control to auto scale the font size of the textblock up or down to fill the available space, hope that’s okay: http://edventuro.us/2010/03/an-auto-scaling-textblock-for-silverlight/

 

M1rage

15 jul 2010

 

Nice job, well done!