在WPF中,什么是在X之间的差异:名称和名称属性?名称、是在、属性、差异

2023-09-02 10:14:56 作者:一见自难忘

标题说明了一切。有时似乎名称和 X:名称属性是可以互换的。

The title says it all. Sometimes it seems that the Name and x:Name attributes are interchangeable.

那么,它们之间有什么明确的差异,而当它是preferable使用一个比其他?

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?

修改答复迄今建议使用 X:名称所有的时间工作正常,但我仍想知道其中的差别是什么。微软把这两个属性在WPF中的第一个版本,因此必须有一些合理的解释。

EDIT Responses so far suggest that using x:Name all the time works fine, but I still want to know what the difference is. Microsoft put these two attributes into the very first release of WPF, so there must be some sensible explanation.

推荐答案

真的是只有一个名字在XAML中, X:名称。的框架,如WPF中,可以选择映射其属性为XAML的的一个X:名称通过使用 RuntimeNamePropertyAttribute 上该指定的类属性映射到X的一个类。XAML名称属性

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的引入了一个名称属性。

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:名称是可用的。所有 X:名称表示XAML是产生一个字段来存储在隐藏类的code的值。什么是运行时就与映射框架依赖。

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想要一个元素preserved在运行时(这是可用的,通过绑定,除其他事项外)和XAML需要知道你想成为在背后类code字段访问哪些元素的名称。 WPF通过标记的名称属性为x的别名绑这两者结合起来:姓名

So, why are there two ways to do the same thing? The simple answer 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:名称,例如允许你通过参照其他的目的通过名称来设置的属性,但在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:名称,AutomationProperties.Name所使用的辅助工具和一些测试工具

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