有时,Name和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.

其他回答

当您在XAML中声明Button元素时,您引用的是在windows运行时中定义的一个名为Button的类。

按钮有很多属性,如背景,文本,边距,.....和一个名为Name的属性。

现在,当您在XAML中声明一个Button时,就像创建一个匿名对象,该对象碰巧有一个名为Name的属性。

一般来说,你不能引用一个匿名对象,但是在WPF框架中,XAML处理器允许你通过给Name属性的任何值来引用该对象。

到目前为止一切顺利。

创建对象的另一种方法是创建命名对象而不是匿名对象。在这种情况下,XAML名称空间有一个名为Name的对象属性(由于它在XAML名称空间中,因此有X:),您可以设置该属性,以便识别对象并引用它。

结论:

Name是特定对象的属性,但X:Name是该对象的一个属性(有一个类定义了一个通用对象)。

我总是使用x:Name变量。 我不知道这是否会影响性能,我只是觉得它更容易,原因如下。 如果您有自己的用户控件驻留在另一个程序集中,只有“Name”属性并不总是足够的。这使得使用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。

我的研究是x:命名为全局变量。但是,Name为局部变量。这是否意味着x:Name可以在XAML文件的任何地方调用,但Name不能。 例子:

<StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />
<Button Content="Example" Name="btn" />
</StackPanel>
<TextBlock Text="{Binding Path=Content, ElementName=btn}" />

你不能绑定属性内容的按钮名称是“btn”,因为它在StackPanel之外