简体   繁体   English

WPF:有没有办法覆盖ControlTemplate的一部分而不重新定义整个样式?

[英]WPF: Is there a way to override part of a ControlTemplate without redefining the whole style?

I am trying to style a WPF xctk:ColorPicker. 我正在尝试设置WPF xctk:ColorPicker。 I want to change the background color of the dropdown view and text without redefining the whole style. 我想更改下拉视图和文本的背景颜色, 而不重新定义整个样式。

I know that the ColorPicker contains eg a part named "PART_ColorPickerPalettePopup". 我知道ColorPicker包含例如名为“PART_ColorPickerPalettePopup”的部件。 Is there a way that I can directly reference this part in my style, providing eg a new Background color only ? 有没有办法,我可以直接在我的风格引用这个部分,提供例如, 一个新的背景颜色的方法吗?

I want to avoid having to redefine all the other properties of "PART_ColorPickerPalettePopup". 我想避免重新定义“PART_ColorPickerPalettePopup”的所有其他属性。

Link to the ColorPicker I am describing 链接到我正在描述的ColorPicker

You can base a Style on another Style and override specfic setters: 您可以将样式基于另一个样式并覆盖特定的setter:

<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>

But you cannot "override" only a part of a ControlTemplate. 但是你不能只“覆盖”ControlTemplate的一部分。 Unfortunately you must then (re)define the entire template as a whole. 不幸的是,您必须(重新)定义整个模板。

Get popup from ColorPicker via VisualTreeHelper and change border properties (child of popup) like this: 通过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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM