I have a custom control (i.e. class derived from System.Windows.Control) and I want to set a default style for it. I know that it is possible to do that by creating themes/generic.xaml and defining the style there. I have done that before and it works.
However, because the style is rather trivial (it is just a dummy rectangle to allow quick mockup), I would like to define the default style in code-only, so that I can keep it close to the class definition and avoid file clutter with the generic.xaml. This is what I have done so far:
static Trailer()
{
// just there to be able to test it alternatively with generic.xaml
FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(Trailer), new FrameworkPropertyMetadata(typeof(Trailer)));
// define the template with dummy geometry
ControlTemplate DefaultTemplate = new ControlTemplate(typeof(Trailer));
FrameworkElementFactory rectFact = new FrameworkElementFactory(typeof(Rectangle));
rectFact.SetValue(Shape.FillProperty, new DynamicResourceExtension(SystemColors.ControlLightBrushKey));
DefaultTemplate.VisualTree = rectFact;
// define the style
Style DefaultStyle = new Style {TargetType = typeof (Trailer)};
Setter setter = new Setter();
setter.Property = Control.TemplateProperty;
setter.Value = DefaultTemplate;
DefaultStyle.Setters.Add(setter);
// register the style in application resources
Application.Current.Resources.Add(typeof(Trailer), DefaultStyle);
}
This works in a very simple test application, but it fails in a more complex setting with other styles/templates where the Control stays empty (default Control style). I haven't been able to figure out what causes the interference, but I take it as evidence that I haven't actually set the default style of my Control with the above code.
Where do I have to set my style, if not in the application resources, in order to get the same behavior as with generic.xaml?