Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

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

, 24 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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:

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.

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:

public class TextBlockUtils
{
  /// <span class="code-SummaryComment"><summary>
</span>  /// Gets the value of the AutoTooltipProperty dependency property
  /// <span class="code-SummaryComment"></summary>
</span>  public static bool GetAutoTooltip(DependencyObject obj)
  {
    return (bool)obj.GetValue(AutoTooltipProperty);
  }
 
  /// <span class="code-SummaryComment"><summary>
</span>  /// Sets the value of the AutoTooltipProperty dependency property
  /// <span class="code-SummaryComment"></summary>
</span>  public static void SetAutoTooltip(DependencyObject obj, bool value)
  {
    obj.SetValue(AutoTooltipProperty, value);
  }
 
  /// <span class="code-SummaryComment"><summary>
</span>  /// 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.
  /// <span class="code-SummaryComment"></summary>
</span>  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);
  }
 
  /// <span class="code-SummaryComment"><summary>
</span>  /// Assigns the ToolTip for the given TextBlock based on whether the text is trimmed
  /// <span class="code-SummaryComment"></summary>
</span>  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:

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)

Share

About the Author

Colin Eberhardt
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
 
-
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionMy vote of 4 Pinmembertabor2530-Sep-13 2:15 
QuestionHow to provide the same feature on Tooltip for Datagrid whose values gets populated in Run PinmemberPriyaRam1119-Jul-13 0:28 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 24 May 2011
Article Copyright 2011 by Colin Eberhardt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid