有时,Name和x:Name属性似乎是可互换的。
那么,它们之间的决定性区别是什么?什么时候使用一种比另一种更可取?
以错误的方式使用它们会对性能或内存产生影响吗?
有时,Name和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之外
其他回答
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.
它们都是一样的东西,很多框架元素本身公开了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.
这不是一个WPF项,而是一个标准的XML项,BtBh已经正确地回答了它,x指的是默认的名称空间。在XML中,如果不给元素/属性加上名称空间前缀,则假定您需要默认名称空间。 因此,只输入Name只不过是x:Name的缩写。关于XML名称空间的更多细节可以在链接文本中找到
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…
我总是使用x:Name变量。 我不知道这是否会影响性能,我只是觉得它更容易,原因如下。 如果您有自己的用户控件驻留在另一个程序集中,只有“Name”属性并不总是足够的。这使得使用x:Name属性更加容易。