x:键&样式中的目标类型 [英] x:Key & TargetType in styles

查看:25
本文介绍了x:键&样式中的目标类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此声明有什么区别(或优势):

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

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

省略 x:Key 属性?

我认为 WPF 将密钥分配给了相同的 x:Type.

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

推荐答案

Style.TargetType 证实了你的怀疑:

The MSDN documentation for Style.TargetType confirms your suspicions:

将 TargetType 属性设置为 TextBlock 类型而不设置 x:Key 隐式地将 x:Key 设置为 {x:Type TextBlock}.这也意味着如果你给上面的 Style 一个 x:Key 值而不是 {x:Type TextBlock} ,则 Style 不会自动应用于所有 TextBlock 元素.相反,您需要将样式显式应用于 TextBlock 元素.

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.

这篇关于x:键&样式中的目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆