user6836683
user6836683

Reputation: 11

Setting implicit style of custom control in WPF

My custom control's default style is defined in Generic.xaml and is working fine.

However, when I try to change the style of my custom control the same way as one can with built in controls nothing happens. In App.xaml I am trying to change the default style of my control by doing the following:

<Style TargetType="{x:Type my:CustomControl}">
  <Setter Property="Background" Value="Red"/>
</Style>

If I set the x:key property of the above style and reference this style using this key all works fine.

Is it correct that the above styling method only works for built in controls and does not work for custom controls, or am I just doing something wrong? Is there a workable solution to achieve this type of styling for custom controls?

Update In this situation my custom control is derived from System.Windows.Window.

Upvotes: 0

Views: 857

Answers (2)

user6836683
user6836683

Reputation: 11

I finally managed to get implicit styling for my custom control to work. Apparently implicit styling might not work for derived controls as the style is not automatically being applied to the control. In order to achieve this one has to manually set the resource reference. My custom control now looks like this:

public class CustomControl : Window
{
    static CustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
    }

    public CustomControl()
    {
        SetResourceReference(StyleProperty, typeof(CustomControl));
    }
}

Upvotes: 0

Arthur Kazykhanov
Arthur Kazykhanov

Reputation: 325

Yes, you are correct. Generic.xaml is used for custom controls, and App.xaml for application-wide resources (including styles for built-in controls). Specifying TargetType for a custom control in App.xaml will not work. So using explicit styles (with x:Key) seems to be the easiest solution.

Upvotes: -1

Related Questions