问题
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 e.g. a part named \"PART_ColorPickerPalettePopup\". Is there a way that I can directly reference this part in my style, providing e.g. 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
回答1:
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.
回答2:
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;
}
来源:https://stackoverflow.com/questions/41570096/wpf-is-there-a-way-to-override-part-of-a-controltemplate-without-redefining-the