Difference between approches for setting DefaultStyleKey

南楼画角 提交于 2020-01-14 08:48:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7646838/difference-between-approches-for-setting-defaultstylekey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!