有时,Name和x:Name属性似乎是可互换的。
那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?
以错误的方式使用它们会对性能或内存产生影响吗?
有时,Name和x:Name属性似乎是可互换的。
那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?
以错误的方式使用它们会对性能或内存产生影响吗?
当前回答
其中一个答案是x:name将在不同的程序语言中使用,如c#,而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之外
它们都是一样的东西,很多框架元素本身公开了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.
它们不是一回事。
x:Name是一个xaml概念,主要用于引用元素。当您为元素赋予x:Name xaml属性时,“指定的x:Name将成为处理xaml时在底层代码中创建的字段的名称,并且该字段包含对该对象的引用。”因此,它是一个由设计器生成的字段,默认情况下具有内部访问权限。
Name是FrameworkElement的现有字符串属性,以xaml属性的形式列出,与任何其他wpf元素属性一样。
因此,这也意味着x:Name可以用于更广泛的对象。这是一种使xaml中的任何东西都可以通过给定名称引用的技术。
其中一个答案是x:name将在不同的程序语言中使用,如c#,而name将用于框架。说实话,我听起来就是这样。
X:如果有自定义控件,Name可能会导致内存问题。它将为NameScope条目保留一个内存位置。
我建议除非迫不得已,否则不要使用x:Name。