Search code examples
.netwpfthemescustom-controlsresourcedictionary

Difference between approches for setting DefaultStyleKey


I am creating a custom control(deriving from Control) and want to define a default theme for the control. Previously all the custom controls I created, I have used

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

with this assembly attribute:

[assembly: ThemeInfo(ResourceDictionaryLocation.SourceAssembly,
ResourceDictionaryLocation.SourceAssembly)]

Alternative approach to do this is (which I have also noticed in some controls) -

public IntegerUpDown()
{
    DefaultStyleKey = typeof(IntegerUpDown);
}

I would like to know the pros and cons of these two approaches and which one to prefer?


Solution

  • I can observe that the first approach asks the dependency property framework to register a default style key. It does that only once (being in a static constructor) and then onwards it is used for all instances of IntegerUpDown. Second approach assignes the Key explicitly when an instance of IntegerUpDown is created on its own. They both seem ok to me.

    MSDN says ...

    Metadata can be overriden so that subclasses can tweak a DP by overriding the property’s metadata, instead of completely re-implementing the property itself.