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.

Try it Out

Install Microsoft Silverlight

35 Comments

Scott Barnes / AUG 03 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.

Darren David / AUG 04 2009

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

Robby Ingebretsen / AUG 05 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 / AUG 05 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 / AUG 05 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 / AUG 05 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 / AUG 05 2009

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

Silverlight Resources Directory Update (06 Aug) / AUG 06 2009

[...] 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 / AUG 11 2009

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

Laila / AUG 13 2009

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

Rajiv / AUG 20 2009

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

Flo / SEP 02 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;
}
}

TextTrimming - Sector 7G / 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: Nov 19 2009, [...]

TextTrimming - Pedro Álvarez Fernández en Geeks / 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 [...]

Elegant Code » Silverlight 4 Beta – Text Trimming / NOV 23 2009

[...] 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 / NOV 25 2009

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

Sally / DEC 14 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 / MAR 02 2010

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

M1rage / JUL 15 2010

Nice job, well done!

Dele O / SEP 24 2010

Thanks for sharing this. I am not strong on the design side and I have always been curious how to get text to show on a faux notebook like the example above. Do you mind sharing the code for that?

Konstantin / MAR 22 2011

Thanks!
Works excellent even for windows phone

enkara / MAY 17 2011

I would be interesting to have a “how to”. For those who are just starting would be a good lesson, although this is not in the scope of the post.

Greg / JUL 01 2011

I tried it out and it always wants to center itself in whatever panel it is in. Kind of annoying. For some reason set HorizontalAlignment=”Left” does not work.

Any ideas?

William / JUL 22 2011

Thanks your. It works good in my project.

I found TextTrimming is already supported in Window Phone 7.1 (Beta), but I cannot wait till its release day.

Greg / AUG 20 2011

I guess you do not respond to questions about your work. This control does not support HorizontalAligment=”Left” . It always centers the text unless the text fills the box of course. Why is it ignoring the positioning?

Ali / OCT 04 2011

@Greg, Set HorizontalContentAlignment to Left

ankit / MAR 12 2012

m not getting how can i use it in code, may anybody post the how to? thanks in advance :)