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

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

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


当前回答

名称:

只能用于FrameworkElement和FrameworkContentElement的后代; 可以通过SetValue()和property-like在代码后面设置。

x:名称:

可以用于几乎所有XAML元素; 不能设置从 通过SetValue()隐藏代码;只能使用属性设置 对象的语法,因为它是一个指令。

在XAML中对一个FrameworkElement或FrameworkContentElement使用这两个指令将导致异常:如果XAML是标记编译,则异常将在标记编译时发生,否则将在加载时发生。

其他回答

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之外

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

Name表示:设置该对象的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.

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

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