Dynamically Generating ToolTip Text

If you’ve been reading my blog for a while now, you probably have noticed that many of my posts show how to do things in WPF which are commonly done in WinForms.  I like to think of my blog as a sort of “bridge” which WinForms developers can use to get from the land of WinForms into the world of WPF.  To keep consistent with that theme, this post demonstrates how you can dynamically generate the content of a tool tip, based on other values only available at runtime.

To keep this example simple, let’s suppose that you have some XML data which describes people and their ages:

Simple XML data

Our goal is to display those names and ages in a list, and have each person’s tool tip explain if the person is a minor, adult, or senior citizen.  The finished product should look like this:

Dynamically generated tooltip messages

We will use ItemsControl to display the people’s names and ages.  Each item in the control will represent a <Person> element.  Since ItemsControl has no knowledge of how to intelligently display an XmlElement, we will have to supply a DataTemplate which provides those smarts:

The magical data template and value converter

The DataTemplate’s root child element is a TextBlock.  That TextBlock’s ToolTip property is bound to the inherited DataContext (for those of you still working on your dependency property x-ray vision, that would be a <Person> XmlElement).  The binding has a custom value converter assigned to it (i.e. an object which implements IValueConverter). 

When the ToolTip value is requested on the TextBlock, the value converter will be invoked and passed a reference to the XmlElement being displayed.  It is the job of that converter to take in a <Person> element and spit out a string which indicates the social category of that person.  Here’s the Convert method of that value converter:

The value converter which generates tooltip messages.

Dynamic ToolTips Source Code — After downloading the file, change the extension from .DOC to .ZIP and then decompress it.

One Response to Dynamically Generating ToolTip Text

  1. George says:

    I can’t run this sample becuase of a compile error:
    Error 1 ”local’ is an undeclared namespace. Line 20, position 10.’ XML is not valid. D:\nwis\Apps\SampleCode\ToolTip_Dynamically Generating ToolTip Text\DynamicToolTips2\Window1.xaml 20 10 DynamicToolTips2

    which is also showin in the pix on this web page as the blue squigly. I also had to copy the code to VS 2008, but it appears you also had the same problem when you took the screenshot. Can you please advise on how to resolve the compile error?


%d bloggers like this: