0
votes

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.

2
Are you setting DefaultStyleKeyProperty.OverrideMetadata in the static constructor or you are doing some workaround?shadow32
"Is it correct that the above styling method only works for built in controls and does not work for custom controls ...?" No, that's not true. You probably did somethings wrong in the declaration of your control. You should show that too.Clemens
Following Clemens comments I tried to replicate my case in a new project. When creating a custom control that inherits from TextBox, implicit styling works fine. However, when using exactly the same set-up and just changing the control to inherit from Window (which was my original problem), implicit styling does not work. Is there some problem with implicit styling when using a Window as the base class as opposed to other controls?user6836683

2 Answers

0
votes

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));
    }
}
-1
votes

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.