如何在WPF中实现鼠标悬停时显示信息气泡?

20

当鼠标悬停在 TextBlock 上时,我想让文本气泡出现。

以下代码是我能够得到的最接近的代码,但它只是将文本注入到 TextBox.Text 中并更改颜色。我希望在鼠标悬停期间在原始 TextBlock 上方显示一个例如 Border/StackPanel/TextBlock 的浮动层

如何创建类似于 web 体验中的悬停面板,例如缩略语标签

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.";
        }

    }
}
2个回答

60

有几种方法可以实现,一种是使用带有自定义样式的工具提示。 或者,您可以使用弹出控件,第三个选项是使用修饰器。

我的直觉告诉我你想要一个工具提示

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

然后您可以使用ToolTipService可附加属性来设置各种选项,包括延迟和工具提示位置。



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接