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:
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:
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 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:
Dynamic ToolTips Source Code — After downloading the file, change the extension from .DOC to .ZIP and then decompress it.