Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Styles not working on Custom Controls

In my App.xaml I have a few implicit styles

<Style TargetType="{x:Type Button}">
   ...Blah...
</Style>

These styles work for control as long as they are not in a custom control I create.

My Control

 public class NavigationControl : Control
 {
     public static readonly DependencyProperty ButtonStyleProperty =
         DependencyProperty.Register("ButtonStyle", typeof(Style), typeof(NavigationControl));

     public Style ButtonStyle
     {
         get { return (Style)GetValue(ButtonStyleProperty); }
         set { SetValue(ButtonStyleProperty, value); }
     }
 }

 static NavigationControl()
 {
     DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationControl), new FrameworkPropertyMetadata(typeof(NavigationControl)));
 }

 public NavigationControl()
 {
 }

My Control Styles and Templates

<ControlTemplate x:Key="NavigationControlTemplate" TargetType="{x:Type controls:NavigationControl}">
   <Button Style="{TemplateBinding ButtonStyle}"
</ControlTemplate>

<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="MinWidth" Value="75"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="Margin" Value="-1"/>
</Style>

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}">
    <Setter Property="Template" Value="{StaticResource NavigationButtonTemplate}"/>
</Style>

<Style TargetType="{x:Type controls:NavigationControl}">
     <Setter Property="Template" Value="{StaticResource NavigationControlTemplate}"/>
     <Setter Property="ButtonStyle" Value="{StaticResource ButtonStyle}"/>
</Style>

Now I would assume that the DefaultButtonStyle's BasedOn would get it from the App level. But it doesnt. The only way to apply the app level style is Override the ButtonStyle by creating a style of type NavigationControl.

Is there a way where the implicit style makes this work?

like image 343
MyKuLLSKI Avatar asked Aug 23 '13 21:08

MyKuLLSKI


1 Answers

Setting BasedOn="{StaticResource {x:Type Button}}" will get you WPF's default button style. If you want to use the style defined in your App.xaml, you'll need to add a key to that style so you could reference it from your control style:

App.xaml

<!-- Your style, just with an added x:Key -->
<Style x:Key="myButtonStyle" TargetType="{x:Type Button}">
   ...
</Style>

<!-- Set the above style as a default style for all buttons -->
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}">

Your control styles and templates

<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}">
    ...
</Style>
like image 76
Adi Lester Avatar answered Sep 21 '22 01:09

Adi Lester