Archive for the ‘Custom Controls’ Category

Textblock showing full text in tooltip when text truncated inside control

June 3, 2012 1 comment

This post describes implementation of custom textblock which will show the full text of the textblock in tooltip when Text can not be shown fully inside the given width of textblock control.

Textblock has property named “TextTrimming”. Value set for this property defines how text is trimmed when it overflows from the edge of Textblock. When “TextTrimming” property is set to “WordEllipsis’ / “CharacterEllipsis” and text value can not be shown fully in given width then text will truncate with “…” (i.e. ellipsis) shown at the end of text. Now one option to show the full text to user is through Tooltip. This can easily be achieved by binding text value as tooltip. However, the heck is showing full text value as tooltip only when needed i.e. when text has been truncated inside Textblock.

Unfortunately, Textblock doesn’t provide any property to indicate that text has been truncated / trimmed. Hence, we need to detect when the text has been truncated i.e. text size has increased beyond the width of textblock’s width. So now the problem is measuring width of text considering text settings applied. “FormattedText” class provided by Microsoft can help us for this. “FormattedText” takes into consideration FontSize, FontStyle, FontWeight, FlowDirection, current culture, etc. while calculating the width of text. Following code snippet shows how to measure text width using “FormattedText”.

Typeface typeface = new Typeface(this.FontFamily,

// FormattedText is used to measure the whole width of the text held up by this container.
FormattedText formmatedText = new FormattedText(

After getting the FormattedText object, just Check

formmatedText.Width > this.ActualWidth

to determine whether text has been truncated or not.

I have attached herewith the full implementation of Custom TextBox class (TextBoxEx) in a word file. In the implementation when Tooltip is opening, it is checking whether text has truncated or not. If text has not truncated then tooltip won’t be displayed (as it is not necessary because full text is anyway visible). Also, in order to show the tooltip, text property of the Textblock should be bound with the tooltip.

ToolTip="{Binding Path=Text, RelativeSource={RelativeSource self}}"

It is pretty obvious that if binding for tooltip is not set then this control will not work.

This one is pretty simple fix for the problem and it works well in the scenarios I have tested so far. Any feedback/bug/enhancement request on this is welcome.