Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When overriding DefaultStyleKey is necessary?

I have just spent like 2 hours trying to figure out why after moving a control from solution A to solution B (along with its style), the control stops showing up (control template was not applied). Turned out I forgot to override default style key. Here is the question: why did it work for solution A?

In DesignerView.cs:

 public class DesignerView : Control {
     // No DefaultStyleKeyProperty.OverrideMetadata here
 }

In Generic.xaml:

<Style TargetType="{x:Type controls:DesignerView}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:DesignerView}">
                <TextBlock Text="Hello" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Of course, my style is a little bit more complicated than that, but anyhow: exactly the same control (class+style, no proper DefaultStyleKeyProperty set) did show up in solution A, but didn't in solution B.

like image 931
Eugene Strizhok Avatar asked Dec 26 '22 13:12

Eugene Strizhok


1 Answers

I guess you are talking about this:

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

Every control needs theme style which define its default template. (Most often for custom controls its defined under Themes\Generic.xaml).

DefaultStyleKeyProperty defines the key used to find the theme style of the control. If you comment out this line, it will pick default template of base class which generally is of type Control. (But since Control does not have any default template defined for it, your control is not shown when you comment out this line)

So, defaultStyleKeyProperty metadata needs to be overriden in static constructor to indicate that its default style is declared under Themes\Generic.xaml.

If you change base class to say Button and you comment out this line, you will see it pick default template of Button class.

So, for your question if your custom control is deriving from Control, you need to override it to provide default template of control. In case deriving from control whose default template is already defined then you can avoid overriding it. It will pick base control style.


That being said for your question

why did it work for solution A?

I suspect you have defined an explicit style somewhere in your solution A which is missing from Solution B. And Solution B doesn't have theme style set as well because of no override of metadata.

like image 104
Rohit Vats Avatar answered May 01 '23 11:05

Rohit Vats