You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WPF Adorner添加Tooltip?连接状态Poor时显示提示

为Adorner添加状态依赖的Tooltip实现方案

核心思路

  • 启用命中测试:当前代码固定设置IsHitTestVisible = false,会阻止鼠标与Adorner交互,导致Tooltip无法触发。需根据ConnectionState动态控制该属性,仅在状态为Poor时开启命中测试。
  • 使用ToolTipService附加属性:WPF的ToolTipService可直接为任何UIElement附加Tooltip,无需替换原有几何图形绘制逻辑,直接在状态切换时配置即可。

修改后的代码实现

public enum ConnectionState
{
    Good = 0,
    Poor = 1
}

public class ConnectionStatusAdorner : Adorner
{
    const ConnectionState DEFAULT_STATE = ConnectionState.Good;

    private readonly DrawingGroup _drawingGroup;
    private readonly RecordButton _recordButton;

    public ConnectionStatusAdorner(RecordButton recordButton)
        : base(recordButton)
    {
        _recordButton = recordButton ?? throw new ArgumentNullException(nameof(recordButton));

        _drawingGroup = new DrawingGroup();
        Focusable = false;

        SetConnectionState(DEFAULT_STATE);
    }

    public void SetConnectionState(ConnectionState state)
    {
        _drawingGroup.Children.Clear();

        var indicatorBrush = ResourceHelper.GetNetworkConnectionStatusBrush(state);
        var pen = new Pen(new SolidColorBrush(Colors.White), 1.5);

        var rect = new Rect
        {
            Location = new Point(_recordButton.Width - 8, 1.5),
            Size = new Size(10, 10)
        };

        var ellipse = new EllipseGeometry(rect);
        var drawing = new GeometryDrawing(indicatorBrush, pen, ellipse);
        _drawingGroup.Children.Add(drawing);

        // 根据状态配置Tooltip与命中测试
        if (state == ConnectionState.Poor)
        {
            IsHitTestVisible = true;
            ToolTipService.SetToolTip(this, "Poor connection");
            ToolTipService.SetIsEnabled(this, true);
        }
        else
        {
            IsHitTestVisible = false;
            ToolTipService.SetToolTip(this, null);
            ToolTipService.SetIsEnabled(this, false);
        }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);
        drawingContext.DrawDrawing(_drawingGroup);
    }
}

说明

  • 状态切换时,仅在Poor模式下开启Adorner的鼠标命中检测,并设置Tooltip内容;Good模式下关闭交互,避免不必要的鼠标响应。
  • 保留了原有几何图形绘制逻辑,无需替换为按钮控件,符合UI设计的合理性要求。

内容的提问来源于stack exchange,提问作者Richard Gale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:23:20