Monday, February 8, 2010

Tooltip for TextBlock in Silverlight (and any other Silverlight control)

I’ve always been used to “.ToolTip” to add a tool tip text to a control. Unfortunately not all Silverlight controls have such a property.

However, Silverlight does provide a class called “ToolTipService” so you can add a Tooltip to almost all Silverlight UI elements.

You can use the class both in the XAML

   1:  <TextBlock x:Name="txtblkNotification" Text="My Textblock">
   2:      <ToolTipService.ToolTip>
   3:          <ToolTip Content="My tool tip for the TextBlock"></ToolTip>
   4:      </ToolTipService.ToolTip>
   5:  </TextBlock>

Or directly in code

   1:  ToolTipService.SetToolTip(txtblkNotification, "My tool tip for the TextBlock");

I hope someone else finds this useful. (I sure did)

13 comments:

  1. Finally!!
    I've searched the whole internet on how to add a Tooltip dynamically to a control (Textblock, ...), and you gave me the answer :)
    Thanx!

    Jim Adorno

    ReplyDelete
  2. @Jim

    I'm happy I could help. Thanks for letting me know.

    Happy coding,
    Justin

    ReplyDelete
  3. Thanks for this snippet..it really helped

    ReplyDelete
  4. @k

    That's wonderful to hear. I'm glad I could help.

    Happy coding,
    Justin

    ReplyDelete
  5. When setting up directly in code, you may want to use a ToolTip instance instead of a string so that later on you can get that ToolTip instance and manipulate it, for example controlling the IsOpen property.

    ToolTip myToolTip = new ToolTip();
    myToolTip.Content = "My tool tip for the TextBlock";
    ToolTipService.SetToolTip(txtblkNotification, myToolTip);

    ReplyDelete
  6. @Jeff

    Great suggestion. Thanks for sharing.

    ReplyDelete
  7. On firefox it's working great. Do you know why on IE9 the tooltip does not appear?

    I thought SilverL was independent of the browser.

    Thanks.

    ReplyDelete
    Replies
    1. My tooltips work fine on both.
      I'm not sure what the problem might be. Perhaps a SL versioning issue.

      Yes, SL is "supposed" to be independent of browser, but unfortunately, not all installs are created equal. I have personally witnessed differences between Chrome SL, IE SL, and Firefox SL. :-/

      Delete
  8. Thanks for the tip. it helped me! :)

    ReplyDelete
  9. thank you very much :)

    ReplyDelete