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

醉酒当歌 提交于 2019-11-26 15:31:29

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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!