Silverlight 4 added TextTrimming="WordEllipsis", which trims the text that a TextBlock displays based on the available width. This blog post describes a simple method for automatically showing the full text as a tooltip whenever the text is trimmed. This is presented as an attached behaviour.
UPDATE: I have updated this solution to support both WPF and Silverlight, see my recent blog post.
The TextTrimming feature of SL4 allows us to worry a little less about the layout of our applications, giving the option to use fixed widths when rendering text. This can be particularly useful if you have to localize your application. However, arbitrarily trimming the text without providing the user with a mechanism to see the full text is not great for the user. A simple solution is to use a tooltip to present the full text.
Detecting whether the a TextBlock's text is being trimmed is not something that is available from the TextBlock's API, there is no IsTrimmed property! A quick search of the Silverlight forums drew a dead end. I did find a decent WPF solution, however this uses various parts of the WPF API that are not present in Silverlight.
Eventually I found that there is a very simple solution ... quoting from the MSDN page on Text and Fonts:
You can detect clipped text programmatically because ActualWidth for a TextBlock always reports the expanded size of the text, even if it does not fit in the layout container. If you know where to read the Width for the layout container that is doing the clipping, you can compare these two values.
Therefore, if a TextBlock is trimming the text, the reported ActualWidth of the TextBlock will be the width that the TextBlock requires to render the text in its entirety, not the actual width of the rendered text!
In the example above, the Width of the TextBlock is set explicity, however it is more common that the width of TextBlock is determined by its parent container, a Grid for example.
To wrap this functionality up into something re-useable, I have created a AutoToolTip attached behaviour. The code for this is shown below:
Most of this is boiler-plate attached behaviour code. The most interesting method is ComputeAutoTooltip which determines whether a tooltip is required. This simply looks at the ActualWidth of the parent and compares it to the ActualWidth of the TextBlock.
To use this code, ensure that your TextBlock is placed within its own Grid, then set the attached property to true. You can see this in action below: