在 WPF 中,x:Name 和 Name 属性之间有什么区别? [英] In WPF, what are the differences between the x:Name and Name attributes?

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

问题描述

有时似乎 Namex:Name 属性是可以互换的.

Sometimes it seems that the Name and x:Name attributes are interchangeable.

那么,它们之间的明确区别是什么,什么时候使用一个比另一个更可取?

So, what are the definitive differences between them, and when is it preferable to use one over the other?

以错误的方式使用它们是否对性能或内存有任何影响?

Are there any performance or memory implications to using them the wrong way?

推荐答案

在 XAML 中确实只有一个名称,x:Name.框架(例如 WPF)可以选择将其属性之一映射到 XAML 的 x:Name,方法是在指定类属性之一映射到XAML 的 x:Name 属性.

There really is only one name in XAML, the x:Name. A framework, such as WPF, can optionally map one of its properties to XAML's x:Name by using the RuntimeNamePropertyAttribute on the class that designates one of the classes properties as mapping to the x:Name attribute of XAML.

这样做的原因是允许在运行时已经具有名称"概念的框架,例如 WPF.例如,在 WPF 中,FrameworkElement 引入了 Name 属性.

The reason this was done was to allow for frameworks that already have a concept of "Name" at runtime, such as WPF. In WPF, for example, FrameworkElement introduces a Name property.

一般来说,一个类不需要为 x:Name 存储名称即可使用.所有 x:Name 对 XAML 的意义是生成一个字段来存储类背后的代码中的值.运行时对该映射执行的操作取决于框架.

In general, a class does not need to store the name for x:Name to be useable. All x:Name means to XAML is generate a field to store the value in the code behind class. What the runtime does with that mapping is framework dependent.

那么,为什么有两种方法可以做同样的事情?简单的答案是因为有两个概念映射到一个属性上.WPF 希望在运行时保留元素的名称(可通过 Bind 等使用),而 XAML 需要知道您希望类背后的代码中的字段可以访问哪些元素.WPF 通过将 Name 属性标记为 x:Name 的别名将这两者联系在一起.

So, why are there two ways to do the same thing? The simple answer is because there are two concepts mapped onto one property. WPF wants the name of an element preserved at runtime (which is usable through Bind, among other things) and XAML needs to know what elements you want to be accessible by fields in the code behind class. WPF ties these two together by marking the Name property as an alias of x:Name.

在未来,XAML 将有更多 x:Name 的用途,例如允许您通过名称引用其他对象来设置属性,但在 3.5 及更早版本中,它仅用于创建字段.

In the future, XAML will have more uses for x:Name, such as allowing you to set properties by referring to other objects by name, but in 3.5 and prior, it is only used to create fields.

是否应该使用一个或另一个实际上是一个风格问题,而不是技术问题.我会把它留给其他人推荐.

Whether you should use one or the other is really a style question, not a technical one. I will leave that to others for a recommendation.

另见AutomationProperties.Name VS x:Name,AutomationProperties.Name 用于辅助功能工具和一些测试工具.

See also AutomationProperties.Name VS x:Name, AutomationProperties.Name is used by accessibility tools and some testing tools.

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

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