Custom Control switching between two styles
I'm making a custom control which has two very different styling needs. One for a basic look, and another for a more advanced look.
My control contains a dependency property for the following enum:
public enum ControlTypes
{
Basic,
Advanced
}
I created two styles in the generic.xaml (with very different templates), and gave each a key.
Inside the change handler for the enum property I'm trying to find the styles and set the correct one.
private stat开发者_如何学运维ic void OnControlTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var myCustomControl = (MyCustomControl)d;
var basicControlStyle = Application.Current.TryFindResource("BasicControlStyle") as Style;
var advancedControlStyle = Application.Current.TryFindResource("AdvancedControlStyle") as Style;
if (myCustomControl.ControlType == ControlTypes.Basic)
myCustomControl.Style = basicControlStyle;
else if (myCustomControl.ControlType == ControlTypes.Advanced)
myCustomControl.Style = advancedControlStyle;
}
The two styles are always null. I'm not sure how to get the styles from inside the generic.xaml. Or is there a better way to swap my styles?
Delete the code in OnControlTypePropertyChanged and put something like this in your XAML. Note that I have bound to a property called IsAdvanced because it was simpler for testing but you can bind to an enum by changing the "True" for {x:Static namespace:nameofyourenum.Value}
<Style TargetType="local:SomeControl">
<Style.Setters>
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="local:SomeControl">
<StackPanel>
<TextBlock Text="DefaultTemplate"></TextBlock>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
<Style.Triggers>
<Trigger Property="IsAdvanced" Value="True">
<Trigger.Setters>
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="local:SomeControl">
<TextBlock Text="Advanced Template"></TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
Note that this still give the programmer who uses your control the ability to completely override the control template and do what they want. Your original approach didn't allow this.
精彩评论