WPF 中的 x:Key 和 x:Name 有什么区别? [英] What's the difference between x:Key and x:Name in WPF?

查看:72
本文介绍了WPF 中的 x:Key 和 x:Name 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WPF中x:Keyx:Name有什么区别?

What's the difference between x:Key and x:Name in WPF?

我不确定真正的区别是什么.

I am not sure what the true difference is.

推荐答案

虽然它们用于类似的目的,但它们不能互换.x:Key 用于作为值添加到字典中的项目,最常用于添加到 ResourceDictionary 的样式和其他资源.在设置 x:Key 属性时,实际上并没有在对象上设置相应的属性,甚至没有设置附加的依赖属性.XAML 处理器只是使用它来了解在调用 Dictionary.Add 时使用什么键.

Although they are used for similar purposes, they are not interchangeable. x:Key is used for items that are being added as values to a dictionary, most often for styles and other resources that are being added to a ResourceDictionary. When setting the x:Key attribute, there is actually no corresponding property on the object or even an attached dependency property being set. It is simply used by the XAML processor to know what key to use when calling Dictionary.Add.

x:Name 有点复杂.它用于将关联名称应用于某个父元素范围内的对象(通常是从 FrameworkElement 派生的对象).这个范围被称为名称范围",最简单的思考方式是想象一个包含 <TextBox x:Name="foo"/> 的 UserControl.

x:Name is a bit more complicated. It's used to apply an associated name to an object (typically an object derived from FrameworkElement) within the scope of some parent element. This scope is called a "namescope" and the easiest way to think of it is to imagine a UserControl that contains a <TextBox x:Name="foo" />.

然后,您可以将 UserControl 的多个实例放在一个 Window 上,而不会与名称foo"发生冲突,因为每个 UserControl 都有自己的名称范围.

You could then put multiple instances of the UserControl onto a Window without the name "foo" colliding because each UserControl has its own namescope.

同样值得注意的是,FrameworkElement 定义了一个名为 Name 的依赖属性,它相当于设置 x:Name.

It's worth noting too that FrameworkElement defines a dependency property called Name that is equivalent to setting x:Name.

另一个区别是 XAML 设计器在代码隐藏中为具有 x:Name 的元素创建成员.对于使用 x:Key 添加到字典中的对象,情况并非如此.

The other difference is that the XAML designer creates members in the code-behind for elements that have an x:Name. This is not true of objects added to a dictionary using x:Key.

您可以在 的 MSDN 文档的备注部分找到有关这些的更多信息x:Name 指令.

这篇关于WPF 中的 x:Key 和 x:Name 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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