有时,Name和x:Name属性似乎是可互换的。
那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?
以错误的方式使用它们会对性能或内存产生影响吗?
有时,Name和x:Name属性似乎是可互换的。
那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?
以错误的方式使用它们会对性能或内存产生影响吗?
当前回答
X:如果有自定义控件,Name可能会导致内存问题。它将为NameScope条目保留一个内存位置。
我建议除非迫不得已,否则不要使用x:Name。
其他回答
Name can also be set using property element syntax with inner text, but that is uncommon. In contrast, x:Name cannot be set in XAML property element syntax, or in code using SetValue; it can only be set using attribute syntax on objects because it is a directive. If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but a parse exception will result if both are specified on the same element. If the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.
X:如果有自定义控件,Name可能会导致内存问题。它将为NameScope条目保留一个内存位置。
我建议除非迫不得已,否则不要使用x:Name。
在XAML中实际上只有一个名称,即x: name。一个框架,比如WPF,可以通过在类上使用RuntimeNamePropertyAttribute将它的一个属性映射到XAML的x:Name属性,这个类指定一个类属性映射到XAML的x:Name属性。
这样做的原因是允许在运行时已经有“Name”概念的框架,例如WPF。例如,在WPF中,FrameworkElement引入了一个Name属性。
一般来说,类不需要存储x: name的名称以使其可用。所有x:Name的意思是XAML是生成一个字段来存储类后面的代码中的值。运行时对映射的处理依赖于框架。
那么,为什么有两种方法来做同样的事情呢?简单的答案是,因为两个概念映射到一个属性上。WPF希望在运行时保留元素的名称(可以通过Bind等方式使用),XAML需要知道您希望类后面代码中的字段可以访问哪些元素。WPF通过将Name属性标记为x:Name的别名将这两者联系在一起。
在未来,XAML会有更多x:Name的用途,比如允许你通过名称引用其他对象来设置属性,但在3.5和更早的版本中,它只用于创建字段。
你应该使用其中一种还是另一种实际上是一个风格问题,而不是技术问题。我将把这个留给其他人来推荐。
请参见AutomationProperties。Name VS x:Name, AutomationProperties。可访问性工具和一些测试工具使用Name。
我总是使用x:Name变量。 我不知道这是否会影响性能,我只是觉得它更容易,原因如下。 如果您有自己的用户控件驻留在另一个程序集中,只有“Name”属性并不总是足够的。这使得使用x:Name属性更加容易。
它们都是一样的东西,很多框架元素本身公开了name属性,但对于那些不公开的元素,你可以使用x:name -我通常只使用x:name,因为它适用于任何东西。
控件可以将名称本身公开为依赖属性(因为它们需要在内部使用该依赖属性),也可以选择不这样做。
更多细节在msdn这里和这里:
Some WPF framework-level applications might be able to avoid any use of the x:Name attribute, because the Name dependency property as specified within the WPF namespace for several of the important base classes such as FrameworkElement/FrameworkContentElement satisfies this same purpose. There are still some common XAML and framework scenarios where code access to an element with no Name property is necessary, most notably in certain animation and storyboard support classes. For instance, you should specify x:Name on timelines and transforms created in XAML, if you intend to reference them from code. If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but an error will result if both are specified on the same element.