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

如何自定义InkToolbarBallpointPenButton调色板悬停行为以显示颜色名称而非RGB值

问题原因

默认InkToolbarBallpointPenButton的调色板颜色项会自动生成ToolTip为颜色的ARGB字符串,不会自动读取预定义颜色的名称,所以会出现悬停显示RGB值的情况。

解决方法

方法1:XAML端直接修改(无额外后台逻辑)

给每个SolidColorBrush添加Tag属性存储颜色名称,再重写调色板项的模板,将ToolTip绑定到Tag值即可,修改后的完整代码如下:

<InkToolbar InitialControls="None">
    <InkToolbar.Resources>
        <!-- 给每个笔刷添加Tag属性存储自定义显示名称 -->
        <BrushCollection x:Key="MyPalette">
            <SolidColorBrush Color="Red" Tag="红色" />
            <SolidColorBrush Color="Blue" Tag="蓝色" />
        </BrushCollection>

        <!-- 重写调色板颜色项样式,修改ToolTip的绑定源 -->
        <Style TargetType="InkToolbarPenConfigurationControl">
            <Setter Property="PaletteItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid Background="{Binding}"
                              ToolTipService.ToolTip="{Binding Tag}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </InkToolbar.Resources>
    <InkToolbarBallpointPenButton Palette="{StaticResource MyPalette}" />
</InkToolbar>

方法2:后台代码批量设置(适合动态生成调色板的场景)

如果你的调色板颜色是运行时动态生成的,可以在页面加载完成后遍历调色板项,批量设置ToolTip:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    // 建立颜色和自定义名称的映射关系
    var colorNameMap = new Dictionary<Color, string>
    {
        { Colors.Red, "红色" },
        { Colors.Blue, "蓝色" }
    };

    // 获取圆珠笔按钮实例
    var penButton = inkToolbar.GetToolButton(InkToolbarTool.BallpointPen) as InkToolbarBallpointPenButton;
    // 遍历可视化树找到调色板的项容器
    var configControl = VisualTreeHelper.GetChild(penButton, 0) as InkToolbarPenConfigurationControl;
    var paletteItemsControl = VisualTreeHelper.GetChild(configControl, 0) as ItemsControl;
    
    // 给每个调色板项设置ToolTip
    for (int i = 0; i < penButton.Palette.Count; i++)
    {
        var brush = penButton.Palette[i] as SolidColorBrush;
        if (colorNameMap.TryGetValue(brush.Color, out string name))
        {
            var item = paletteItemsControl.ContainerFromIndex(i) as FrameworkElement;
            ToolTipService.SetToolTip(item, name);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:48:04