有时,Name和x:Name属性似乎是可互换的。

那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?

以错误的方式使用它们会对性能或内存产生影响吗?


当前回答

唯一的区别是,如果你在同一个程序集中使用用户控件到一个控件中,那么Name将不能识别你的控件,你将得到一个错误“在同一个程序集中使用x:Name控件”。 所以x:Name是WPF中命名控件的WPF版本。Name只是用作Winform Legacy。他们想在WPF和winforms中区分控件的命名,因为他们使用Xaml中的属性来标识控件与其他程序集,他们使用x:表示控件的名称。

请记住,不要为控件命名,因为它在内存中是空白的,它会给你一个警告,说明名称已应用于控件,但它从未使用过。

其他回答

x:Name的意思是:在后面的代码中创建一个字段来保存对该对象的引用。

Name表示:设置该对象的Name属性。

这不是一个WPF项,而是一个标准的XML项,BtBh已经正确地回答了它,x指的是默认的名称空间。在XML中,如果不给元素/属性加上名称空间前缀,则假定您需要默认名称空间。 因此,只输入Name只不过是x:Name的缩写。关于XML名称空间的更多细节可以在链接文本中找到

它们都是一样的东西,很多框架元素本身公开了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.

在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。

The specified x:Name becomes the name of a field that is created in the underlying code when XAML is processed, and that field holds a reference to the object. In Silverlight, using the managed API, the process of creating this field is performed by the MSBuild target steps, which also are responsible for joining the partial classes for a XAML file and its code-behind. This behavior is not necessarily XAML-language specified; it is the particular implementation that Silverlight applies to use x:Name in its programming and application models.

阅读更多关于MSDN…