WPF: 是否有一种方法可以在不重新定义整个样式的情况下覆盖控件模板的部分内容?

10

我想要调整 WPF xctk:ColorPicker 的样式,只修改下拉视图和文本的背景颜色,而不需要重新定义整个样式。

我知道 ColorPicker 包含一个名为“PART_ColorPickerPalettePopup”的部件。是否有一种方法可以在我的样式中直接引用此部分,仅提供新的背景颜色而无需重新定义“PART_ColorPickerPalettePopup”的所有其他属性?

我希望避免重新定义“PART_ColorPickerPalettePopup”的所有其他属性。

链接到我描述的 ColorPicker

2个回答

11
您可以基于另一个样式并覆盖特定的设置器来创建一个样式:
<Style x:Key="myStyle" TargetType="xctk:ColorPicker" BasedOn="{StaticResource {x:Type xctk:ColorPicker}}">
    <!-- This will override the Background setter of the base style -->
    <Setter Property="Background" Value="Red" />
</Style>

但是您无法仅“覆盖” ControlTemplate 的部分内容。不幸的是,您必须将整个模板作为一个整体(重新)定义。


7

通过 VisualTreeHelper 从 ColorPicker 获取弹出窗口,并更改边框属性(弹出窗口的子元素)如下:

   private void colorPicker_Loaded(object sender,RoutedEventArgs e)
    {
        Popup popup = FindVisualChildByName<Popup> ((sender as DependencyObject),"PART_ColorPickerPalettePopup");
        Border border = FindVisualChildByName<Border> (popup.Child,"DropDownBorder");
        border.Background = Brushes.Yellow;
    }

    private T FindVisualChildByName<T>(DependencyObject parent,string name) where T:DependencyObject
    {
        for (int i = 0;i < VisualTreeHelper.GetChildrenCount (parent);i++)
        {
            var child = VisualTreeHelper.GetChild (parent,i);
            string controlName = child.GetValue (Control.NameProperty) as string;
            if (controlName == name)
            {
                return child as T;
            }
            else
            {
                T result = FindVisualChildByName<T> (child,name);
                if (result != null)
                    return result;
            }
        }
        return null;
    }

你值得一枚奖牌。很棒的解决方案! - Avrohom

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