x:Key & TargetType in styles

这一生的挚爱 提交于 2019-12-10 01:52:18

问题


Is there any difference (or advantage) for use this statement:

Style x:Key="{x:Type DataGridCell}" TargetType="{x:Type DataGridCell}"

with omitting the x:Key attribute?

I think WPF assigns the key to the same x:Type under the hood.


回答1:


The MSDN documentation for Style.TargetType confirms your suspicions:

Setting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type TextBlock}. This also means that if you give the above Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. Instead, you need to apply the style to the TextBlock elements explicitly.

If the resource dictionary key of a style is a type, that style is used as the default style for all instances of that type that don't explicitly specify a style. Since the target type is usually supplied, the syntax of omitting the key is simply a shortcut for defining a default style.



来源:https://stackoverflow.com/questions/8108923/xkey-targettype-in-styles

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