x:Key & TargetType in styles

2019-04-20 02:28发布

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条回答
祖国的老花朵
2楼-- · 2019-04-20 02:33

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.

查看更多
登录 后发表回答