Monday, June 2, 2008

[C#] Using TooltipService

NOTE: As of Silverlight 2 Beta 2, this seems to be borked. Not sure why yet... I'll have a look later.

Today I was trying to add a simple tooltip to a bunch of small Canvas' in my Silverlight project. After a little digging I found that
  • (a) there is a .NET class called Tooltip which does this functionality for me and
  • (b) many controls lack a ToolTip property [such as TextBox, TextBlock, Canvas etc...]
To add a ToolTip to these controls, we are able to use the ToolTip attached property via ToolTipService. I am unfamiliar with attached properties, and I will be going over them in detail soon, however, for now I'm just going to drone on about using the ToolTipService in C# since it took me a little digging to find any kind of example [most were examples in XAML only].
  // Create a Tooltip
ToolTip nameTip = new ToolTip();

// Set the content [here I use text, but apparently it can be more complex]
nameTip.Content = "Testing ToolTipService";

// Use ToolTipService to attach the ToolTip to my Canvas.
ToolTipService.SetToolTip(myCanvas, nameTip);
Note, you may need to add the System.Windows.Controls reference to your project for this to work... I can't recall if that assembly is added by default when you create a project in VS2008.

ToolTipService Documentation

2 comments:

Anonymous said...

//add this ref to project
System.Windows.Controls.Extended

//using a TextBlock for ToolTip
//Adding to an Image
//Adding Image to ListBox

TextBlock tb = new TextBlock();
tb.Text = "your text here"

//Now add using ToolTip Service
ToolTipService.SetToolTip(Image, tb);

//add to Listbox
ListBox.Items.Add(Image);

Works for me.

Anonymous said...

//My Goof forget adding this ref
System.Windows.Controls.Extended

Just make sure System.Windows.Controls
is referenced in your project