Back to Home

On Demand Tooltip for WPF TextBlock

November 24, 20142 minutes read
On Demand Tooltip for WPF TextBlock

According to MSDN, a tooltip

Represents a small rectangular pop-up window that displays a brief description of a control’s purpose when the user rests the pointer on the control.

Setting a tooltip is really easy with WPF controls.

<Button Content="Save"
ToolTip="Save the contents" />

But there are some situations when user want to see tool tip, only when the text is really not readable. Whether the text block size may become smaller, when user re-size the Window. Or the text becomes more lengthy in a text box, where the maximum width of the text box is really less.


A possible way is to measure the text block / text box with maximum size, which will give you the DesiredSize. Comparing that size with actual size is the right way to decide whether or not showing the toool tip. The following simple code snippet can do this trick.

private void ShowTooltipOnDemand()
textBox.Measure(new Size(Double.MaxValue, Double.MaxValue));
var width = textBox.DesiredSize.Width;

if (textBox.ActualWidth < width)
ToolTipService.SetToolTip(textBox, textBox.Text);
ToolTipService.SetToolTip(textBox, null);

This method can be called from SizeChanged and TextChanged event for text box. That will make the text always readable. (For text block, only SizeChanged is enough)

Happy Coding!!!