简体   繁体   中英

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

Link to the ColorPicker I am describing

You can base a Style on another Style and override specfic setters:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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