xaml文件中控件的x:name和name有什么区别? [英] Is there any difference in x:name and name for controls in xaml file?
问题描述
我是Silverlight的新手.
当我使用Visual Studio将一些控件添加到我的xaml文件中时,它使用Name属性设置了控件名称,但是还存在x:Name.
有什么区别,何时使用它们?
谢谢.
I am new in Silverlight.
When I add some control to my xaml file with Visual Studio it set controls name with Name property, but there is also x:Name.
Is there any difference and when to use each of them?
Thanks.
推荐答案
简介
是的,有区别.最重要的是,x:Name
可以用于不具有自身Name
属性的对象元素.
Yes there is a difference. The bottom line is that x:Name
can be used on object elements that do not have Name
properties of their own.
详细说明
您只能在表示确实具有Name
属性的对象的元素上使用Name
.例如,任何源自FrameworkElement
的东西.
You can only use Name
on an element that represents an object that actually does have a Name
property. For example anything that derives from FrameworkElement
.
x:Name
属性可以放置在表示对象的任何元素上,无论该对象是否实际上具有Name
属性.如果对象确实具有Name
属性,则将为它分配x:Name
值,因此同一元素上不能同时具有x:Name
和Name
.
The x:Name
attribute may be placed on any element that represents an object regardless of whether that object actually has a Name
property. If the object does have a Name
property then the value of x:Name
will be assigned to it hence you can't have both x:Name
and Name
on the same element.
当对象具有Name
属性或x:Name
属性时,该属性的值与对象树中的对象条目相关联. FrameworkElement
的FindName
方法通过对象树可以找到对象. FindName
可以按名称查找对象,即使该对象不使用自身的Name
属性,因为它使用记录在对象树中的名称.
When an object has a Name
property or an x:Name
property the value of that property is associated with the objects entry in the object tree. It is via the object tree that the FindName
method of a FrameworkElement
can find an object. FindName
can find objects by name even if that object does not carry a Name
property of its own since it uses the name recorded in the object tree.
UserControl
的自动生成的代码将包含具有Name
或x:Name
属性的任何元素的字段定义.生成的InitialiseComponent
方法将使用FindName
方法将值分配给这些字段.
The autogenerated code for a UserControl
will contain field definitions for any element that that has a Name
or x:Name
property. The InitialiseComponent
method that is generated will use the FindName
method to assign values to these fields.
示例
上面的Xaml创建两个类型为Grid
的字段LayoutRoot
和类型为SolidColorBrush
的MyBrush
.如果将x:Name="LayoutRoot"
更改为Name="LayoutRoot"
,则不会有任何改变. Grid
具有Name
属性.但是,尝试将x:Name="MyBrush"
更改为Name="MyBrush"
.这不起作用,因为SolidColorBrush
没有名称属性.使用上面的Xaml,您可以执行以下代码:-
The above Xaml creates two fields LayoutRoot
of type Grid
and MyBrush
of type SolidColorBrush
. If you were to change x:Name="LayoutRoot"
to Name="LayoutRoot"
that would change nothing. Grid
has a Name
property. However try changing x:Name="MyBrush"
to Name="MyBrush"
. That doesn't work because SolidColorBrush
doesn't have a name property. With the above Xaml you can then do code like this:-
public MainPage()
{
InitializeComponent();
MyBrush.Color = Colors.LightGray;
}
打开InitializeComponent
的定义,看看自动生成的代码.
Open the definition of InitializeComponent
and take a look at the auto generated code.
这篇关于xaml文件中控件的x:name和name有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!