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.

Leave a Reply

Your email address will not be published. Required fields are marked *