如何在文本框上显示气球提示?

13

我有一个使用XAML和MVVM的C# WPF应用程序。我的问题是:如何在用户输入一些无效数据时,在文本框上方显示气球工具提示?

我想使用微软的原生气球控件来实现这个功能。我该如何将其集成到我的应用程序中呢?


1
其他关于此问题的SO帖子:https://dev59.com/m3E95IYBdhLWcg3wb9db。可能会对您有所帮助。他们也提到了与您相同的URL。 - Christophe Geers
2
这些都没有使用本地的Windows气球。我已经尝试过了,但并没有帮助,这就是为什么我发布了自己的问题。 - qJake
4个回答

12

只需添加对System.Windows.FormsC:\Program Files\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\WindowsFormsIntegration.dll的引用,然后执行以下操作:

    WindowsFormsHost host =new WindowsFormsHost();

    var toolTip1 = new System.Windows.Forms.ToolTip();

    toolTip1.AutoPopDelay = 5000;
    toolTip1.InitialDelay = 1000;
    toolTip1.ReshowDelay = 500;
    toolTip1.ShowAlways = true;
    toolTip1.IsBalloon = true;
    toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
    toolTip1.ToolTipTitle = "Title:";

    System.Windows.Forms.TextBox tb = new System.Windows.Forms.TextBox();
    tb.Text="Go!";
    toolTip1.SetToolTip(tb, "My Info!");
    host.Child = tb;
    grid1.Children.Add(host);  //a container for windowsForm textBox 

这是一个关于在WPF中使用WinForm工具提示气球的示例:

在此输入图片描述

希望能对你有所帮助!


1
你能链接到那个ToolTip类吗?是http://msdn.microsoft.com/en-us/library/system.windows.controls.tooltip.aspx吗? - Ian Boyd
9
这里不仅使用了WinForms的提示框,还在WPF应用程序中嵌入了一个WinForms的文本框。这似乎是一种相当低效的方法。 - Joe White
1
这个不起作用,也不是我要找的。我不仅不想要对 System.Windows.Forms 和 WindowsFormsIntegration 的引用,而且代码也没有像应该一样产生工具提示气泡,它只是在我的网格中填充了一个表单文本框。 - qJake
添加WindowsFormsIntegration引用,路径为C:\Program Files\Reference Assemblies\Microsoft\Framework\v4.0\WindowsFormsIntegration.dll,并调整你的文本框大小。 - ARZ
1
除非微软提供了本地的WPF工具提示,否则就没有可用的。- 为什么没有人建议我使用一些P/Invokes来本地调用工具提示呢? - qJake
显示剩余7条评论

3

这个 BalloonDecorator 项目 是我正在使用的一个项目,用于显示帮助提示和错误通知。我知道您可以修改错误模板以显示此装饰器,就像您可以显示图标而不是红色边框一样。使用装饰器的好处是您可以使其看起来任何你想要的,并且不必依赖 WinForms。

BalloonDecorator.cs

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

namespace MyNamespace
{
public class BalloonDecorator : Decorator
{
    private static double _thickness = 0;
    private static int OpeningGap = 10;

    public static readonly DependencyProperty BackgroundProperty =
        DependencyProperty.Register("Background", typeof (Brush), typeof (BalloonDecorator));

    public static readonly DependencyProperty BorderBrushProperty =
        DependencyProperty.Register("BorderBrush", typeof (Brush), typeof (BalloonDecorator));

    public static readonly DependencyProperty PointerLengthProperty = 
        DependencyProperty.Register("PointerLength", typeof (double), typeof (BalloonDecorator),
        new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender |
        FrameworkPropertyMetadataOptions.AffectsMeasure));

    public static readonly DependencyProperty CornerRadiusProperty = 
        DependencyProperty.Register("CornerRadius", typeof (double), typeof (BalloonDecorator),
        new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender |
        FrameworkPropertyMetadataOptions.AffectsMeasure));

    public Brush Background
    {
        get { return (Brush) GetValue(BackgroundProperty); }
        set { SetValue(BackgroundProperty, value); }
    }

    public Brush BorderBrush
    {
        get { return (Brush) GetValue(BorderBrushProperty); }
        set { SetValue(BorderBrushProperty, value); }
    }

    public double PointerLength
    {
        get { return (double) GetValue(PointerLengthProperty); }
        set { SetValue(PointerLengthProperty, value); }
    }

    public double CornerRadius
    {
        get { return (double) GetValue(CornerRadiusProperty); }
        set { SetValue(CornerRadiusProperty, value); }
    }

    protected override Size ArrangeOverride(Size arrangeSize)
    {
        UIElement child = Child;
        if (child != null)
        {
            double pLength = PointerLength;
            Rect innerRect =
                Rect.Inflate(new Rect(pLength, 0, Math.Max(0, arrangeSize.Width - pLength), arrangeSize.Height),
                             -1 * _thickness, -1 * _thickness);
            child.Arrange(innerRect);
        }

        return arrangeSize;
    }

    protected override Size MeasureOverride(Size constraint)
    {
        UIElement child = Child;
        Size size = new Size();
        if (child != null)
        {
            Size innerSize = new Size(Math.Max(0, constraint.Width - PointerLength), constraint.Height);
            child.Measure(innerSize);
            size.Width += child.DesiredSize.Width;
            size.Height += child.DesiredSize.Height;
        }

        Size borderSize = new Size(2 * _thickness, 2 * _thickness);
        size.Width += borderSize.Width + PointerLength;
        size.Height += borderSize.Height;

        return size;
    }

    protected override void OnRender(DrawingContext dc)
    {
        Rect rect = new Rect(0, 0, RenderSize.Width, RenderSize.Height);

        dc.PushClip(new RectangleGeometry(rect));
        dc.DrawGeometry(Background, new Pen(BorderBrush, _thickness), CreateBalloonGeometry(rect));
        dc.Pop();
    }

    private StreamGeometry CreateBalloonGeometry(Rect rect)
    {
        double radius = Math.Min(CornerRadius, rect.Height / 2);
        double pointerLength = PointerLength;

        // All the points on the path
        Point[] points =
            {
                new Point(pointerLength + radius, 0), new Point(rect.Width - radius, 0), // Top
                new Point(rect.Width, radius), new Point(rect.Width, rect.Height - radius), // Right
                new Point(rect.Width - radius, rect.Height), // Bottom
                new Point(pointerLength + radius, rect.Height), // Bottom
                new Point(pointerLength, rect.Height - radius), // Left
                new Point(pointerLength, radius) // Left
            };

        StreamGeometry geometry = new StreamGeometry();
        geometry.FillRule = FillRule.Nonzero;
        using (StreamGeometryContext ctx = geometry.Open())
        {
            ctx.BeginFigure(points[0], true, true);
            ctx.LineTo(points[1], true, false);
            ctx.ArcTo(points[2], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
            ctx.LineTo(points[3], true, false);
            ctx.ArcTo(points[4], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
            ctx.LineTo(points[5], true, false);

            ctx.ArcTo(points[6], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);

            // Pointer
            if (pointerLength > 0)
            {
                ctx.LineTo(rect.BottomLeft, true, false);
                ctx.LineTo(new Point(pointerLength, rect.Height - radius - OpeningGap), true, false);
            }
            ctx.LineTo(points[7], true, false);

            ctx.ArcTo(points[0], new Size(radius, radius), 0, false, SweepDirection.Clockwise, true, false);
        }
        return geometry;
    }
}
}

请确保将此类的命名空间加载到XAML导入中(我使用一个名为“Framework”的命名空间),这样就很容易使用了:

    <Framework:BalloonDecorator  Background="#FFFF6600" PointerLength="50"
     CornerRadius="5" Opacity=".9" Margin="200,120,0,0"
     HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="{Binding UnitPriceChangedBalloonVisibility}">
        <Border CornerRadius="2">
            <Border CornerRadius="2">
                <Button Height="Auto" Command="{Binding CloseUnitPriceChangedBalloonCommand}" Background="Transparent" BorderBrush="{x:Null}">
                <TextBlock Text="Please review the price. The Units have changed."
                     HorizontalAlignment="Left"
                     VerticalAlignment="Top"
                     FontStyle="Italic"
                     TextWrapping="Wrap"
                     Margin="10"
                     />
                     </Button>
            </Border>
        </Border>
    </Framework:BalloonDecorator>

显然,我将可见性绑定在一个绑定上,但您可以将其设置为true并将其放置在Validation.ErrorTemplate中。
希望这可以帮助!

是的,这是一个气球,但我必须覆盖在其中使用的按钮的鼠标悬停样式,因为它在Windows 7上看起来很糟糕,而且位置也不正确(理想情况下,它不应该是表单布局的一部分,而是一个独立的浮动实体)。很抱歉,这不是我要找的东西。 - qJake
没问题。如果你不介意使用混合的WinForms/WPF解决方案,那么除了编写一个WPF封装WinAPI的工具提示之外,这可能是你最好的选择。 - Bahri Gungor
当然,我喜欢它,但仅当我尝试调用它时不会抛出NullReferenceExceptions异常。 ;) - qJake

2
我一直在寻找比BalloonDecorator更好的解决方案,然后发现了http://www.hardcodet.net/projects/wpf-notifyicon项目。它使用WinAPI在最低级别上操作,这可能会为您构建自己的解决方案提供一个起点。乍一看,它似乎可以潜在地解决问题,但我还没有足够的时间来验证BalloonTip是否可以按照您所描述的那样行事。
祝你的项目好运!

这是一个可能性...我更喜欢使用本地的Windows调用,但我可能不得不接受类似这样的东西。感谢提供链接。 - qJake
没问题。如果你找到了合适的解决方案,请发布出来,这样我们其他人就可以看到你取得的成果了。 - Bahri Gungor
1
所以,我宁愿使用自定义的WPF窗口作为工具提示,而不是将旧的Winforms内容合并到我的应用程序中。由于这个项目是最好的例子,因此它得到了赏金。如果您可以处理旧的文本框(或其他控件),则将Winforms项添加到您的WPF窗口是可行的选择,但这不是我要寻找的。另一种解决方案是在Win32中P/Invoke工具提示调用,但在WPF中创建自定义窗口可能更容易/更快。 - qJake

1

2
我宁愿不要引用过时的 System.Windows.Forms 库。 - qJake

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