How can I make a hover info bubble appear on mouseover in WPF?

Edward Tanguay picture Edward Tanguay · Dec 3, 2009 · Viewed 34.2k times · Source

I want to make bubble of text appear when the mouse is over a TextBlock.

The following code is the closest I can get but it just injects text into TextBox.Text itself and changes the color. I want to have a e.g. Border/StackPanel/TextBlock above the original textblock floating on a different layer during mouseover.

How can I make a hover panel similar to a web experience with the acronym tag?

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace TestHover29282
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            TextBlock tb = new TextBlock();
            tb.Text = "test";

            tb.MouseEnter += new MouseEventHandler(tb_MouseEnter);
            tb.MouseLeave += new MouseEventHandler(tb_MouseLeave);

            MainStackPanel.Children.Add(tb); 
        }

        void tb_MouseLeave(object sender, MouseEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            tb.Background = new SolidColorBrush(Colors.Transparent);
            tb.Text = "test";
        }

        void tb_MouseEnter(object sender, MouseEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            tb.Background = new SolidColorBrush(Colors.Orange);
            tb.Text += " - this should be in a popup bubble.";
        }

    }
}

Answer

Muad'Dib picture Muad'Dib · Dec 3, 2009

couple of ways you could do it, one use a tool tip with a custom style. alternativly, you can use a popup control, a third option would be to use an adorner.

My gut says you want a tooltip, tho.

<TextBlock ToolTip="stuff, could even be a custom control, etc" Text="my text" />

you can then use the ToolTipService attachable properties to set a variety of options for said tooltip, from delays to tooltip positions