You need to enable JavaScript to run this app. 如何在WinUI-3 C#中创建并实现带Title和Description附加属性的CustomToolTip
优惠活动
大模型
产品
解决方案
定价
更多

如何在WinUI-3 C#中创建并实现带Title和Description附加属性的CustomToolTip

实现自定义附加属性CustomToolTip(含Title和Description)

一、C# 自定义附加属性实现

创建CustomToolTip类作为附加属性的宿主,通过WinUI的依赖属性系统注册Title和Description两个附加属性,代码如下:

using Microsoft.UI.Xaml;

public class CustomToolTip
{
    // 注册Title附加属性
    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.RegisterAttached(
            "Title",
            typeof(string),
            typeof(CustomToolTip),
            new PropertyMetadata(null, OnTitleChanged));

    // 注册Description附加属性
    public static readonly DependencyProperty DescriptionProperty =
        DependencyProperty.RegisterAttached(
            "Description",
            typeof(string),
            typeof(CustomToolTip),
            new PropertyMetadata(null, OnDescriptionChanged));

    // Title属性的Get方法
    public static string GetTitle(DependencyObject obj)
    {
        return (string)obj.GetValue(TitleProperty);
    }

    // Title属性的Set方法
    public static void SetTitle(DependencyObject obj, string value)
    {
        obj.SetValue(TitleProperty, value);
    }

    // Description属性的Get方法
    public static string GetDescription(DependencyObject obj)
    {
        return (string)obj.GetValue(DescriptionProperty);
    }

    // Description属性的Set方法
    public static void SetDescription(DependencyObject obj, string value)
    {
        obj.SetValue(DescriptionProperty, value);
    }

    // Title属性值变化时的回调(可按需添加逻辑)
    private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // 比如更新自定义ToolTip的标题显示
    }

    // Description属性值变化时的回调(可按需添加逻辑)
    private static void OnDescriptionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // 比如更新自定义ToolTip的描述内容
    }
}

二、XAML 用法示例

  1. 先在XAML根元素中引入自定义类所在的命名空间(假设类在YourApp.Controls下):
<Window x:Class="YourApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="using:YourApp.Controls">
  1. 给目标控件设置附加属性,效果和你提供的WinUI Ribbon示例一致:
<ribbon:RibbonTab Header="radRibbonView"> 
    <ribbon:RibbonGroup Header="Home"> 
        <ribbon:RibbonButton x:Name="radRibbonGroupClipboard"  
                            controls:CustomToolTip.Description="显示剪贴板任务选项。" 
                            controls:CustomToolTip.Title="剪贴板" /> 
    </ribbon:RibbonGroup> 
</ribbon:RibbonTab>

如果需要实现鼠标悬停时弹出包含Title和Description的提示面板,可以在CustomToolTip类中扩展逻辑,比如监听控件的PointerEntered事件,动态生成自定义弹窗并绑定属性值。

内容的提问来源于stack exchange,提问作者Budding bro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:00:19