Click here to Skip to main content
15,867,488 members
Articles / Desktop Programming / WPF

Automatically Showing ToolTips on a Trimmed TextBlock (Silverlight + WPF)

Rate me:
Please Sign up or sign in to vote.
4.94/5 (9 votes)
24 May 2011CPOL2 min read 29.7K   12   3
How to automatically show ToolTips on a trimmed TextBlock (Silverlight + WPF)

Both WPF and Silverlight have a property 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 and works in both WPF and Silverlight.

A few weeks ago, I blogged about a Silverlight solution for automatically adding tooltips when a TextBlock Text is trimmed and renders an ellipsis. I found a decent looking WPF solutions on the web and linked it in my article, however, based on the comments to my previous blog post, it looks like the WPF solution didn’t work too well, failing to respect font size, etc. In this blog post, I have updated my solution to be cross-platform, working on WPF and Silverlight.

To briefly recap, my solution for automatically adding tooltips to trimmed text relies on the slightly odd behaviour of the TextBlock where its ActualWidth is reported as the width of the text without trimming:

Image 1

In order to determine whether to show a tooltip, all you have to do is compare the ActualWidth of the TextBlock to the ActualWidth of its parent.

However, the WPF TextBlock does not have this same quirky behaviour, so a completely different approach is required. The other solutions I have seen involve using the low-level WPF drawing APIs to compute the size of the rendered text, however, there is a simpler solution to this problem …

UPDATE: I originally wrote about a method of finding the overall text width from various internal fields within the TextBlock via reflection, as shown below. However, a kind reader of my blog, Daniel Fihnn, pointed out that there is a simpler solution that does not require any reflection.

Image 2

Daniel pointed out that the width of the TextBlock without the trimming can be obtained using the Measure method. This method is typically used by panels during layout, the Measure method is invoked with the size made available to the element, calling this method causes the element to update its DesiredSize property. Therefore, if you invoke Measure on a TextBlock which has trimming enabled, giving it an infinite available space, its DesiredSize property will report the width that the text would occupy without trimming.

The ComputeAutoTooltip method of the attached behaviour I described in my previous post is updated to have a completely different WPF implementation:

C#
public class TextBlockUtils
{
  /// <summary>
  /// Gets the value of the AutoTooltipProperty dependency property
  /// </summary>
  public static bool GetAutoTooltip(DependencyObject obj)
  {
    return (bool)obj.GetValue(AutoTooltipProperty);
  }
 
  /// <summary>
  /// Sets the value of the AutoTooltipProperty dependency property
  /// </summary>
  public static void SetAutoTooltip(DependencyObject obj, bool value)
  {
    obj.SetValue(AutoTooltipProperty, value);
  }
 
  /// <summary>
  /// Identified the attached AutoTooltip property. 
  /// When true, this will set the TextBlock TextTrimming
  /// property to WordEllipsis, and display a tooltip with the full text 
  /// whenever the text is trimmed.
  /// </summary>
  public static readonly DependencyProperty AutoTooltipProperty = 
	DependencyProperty.RegisterAttached("AutoTooltip",
        	typeof(bool), typeof(TextBlockUtils), 
	new PropertyMetadata(false, OnAutoTooltipPropertyChanged));
 
  private static void OnAutoTooltipPropertyChanged
	(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    TextBlock textBlock = d as TextBlock;
    if (textBlock == null)
      return;
 
    if (e.NewValue.Equals(true))
    {
      textBlock.TextTrimming = TextTrimming.WordEllipsis;
      ComputeAutoTooltip(textBlock);
      textBlock.SizeChanged += TextBlock_SizeChanged;
    }
    else
    {
      textBlock.SizeChanged -= TextBlock_SizeChanged;
    }
  }
 
  private static void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e)
  {
    TextBlock textBlock = sender as TextBlock;
    ComputeAutoTooltip(textBlock);
  }
 
  /// <summary>
  /// Assigns the ToolTip for the given TextBlock based on whether the text is trimmed
  /// </summary>
  private static void ComputeAutoTooltip(TextBlock textBlock)
  {
#if WPF
    textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
    var width = textBlock.DesiredSize.Width;
 
    if (textBlock.ActualWidth < width)
    {
      ToolTipService.SetToolTip(textBlock, textBlock.Text);
    }
    else
    {
      ToolTipService.SetToolTip(textBlock, null);
    }
 
#else
    FrameworkElement parentElement = 
	VisualTreeHelper.GetParent(textBlock) as FrameworkElement;
    if (parentElement != null)
    {
      if (textBlock.ActualWidth > parentElement.ActualWidth)
      {
        ToolTipService.SetToolTip(textBlock, textBlock.Text);
      }
      else
      {
        ToolTipService.SetToolTip(textBlock, null);
      }
    }
#endif 
  }
}

This code now works in both a WPF and a Silverlight context. Here’s a screenshot of it working in WPF:

Image 3

You can download the full source code, including the WPF and Silverlight demo here.

Thanks to Daniel Fihnn for a much improved WPF version of this code!

Regards,
Colin E.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Scott Logic
United Kingdom United Kingdom
I am CTO at ShinobiControls, a team of iOS developers who are carefully crafting iOS charts, grids and controls for making your applications awesome.

I am a Technical Architect for Visiblox which have developed the world's fastest WPF / Silverlight and WP7 charts.

I am also a Technical Evangelist at Scott Logic, a provider of bespoke financial software and consultancy for the retail and investment banking, stockbroking, asset management and hedge fund communities.

Visit my blog - Colin Eberhardt's Adventures in .NET.

Follow me on Twitter - @ColinEberhardt

-

Comments and Discussions

 
QuestionMy vote of 4 Pin
tabor2530-Sep-13 2:15
tabor2530-Sep-13 2:15 
AnswerRe: My vote of 4 Pin
Krishtal2-Apr-15 6:12
Krishtal2-Apr-15 6:12 
QuestionHow to provide the same feature on Tooltip for Datagrid whose values gets populated in Run Pin
PriyaRam1119-Jul-13 0:28
PriyaRam1119-Jul-13 0:28 
Hi,

Since my datagrid is getting generated in run time which doesnt have textblock binding like you have mentioned in the code,i wanted to know how to link the event OnAutoTooltipPropertyChanged.
As in your code,inside the OnAutoTooltipPropertyChanged event it finds the textblock which is found in xaml.
How do i get the textblock which gets generated in runtime inside that event?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.