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.
I am new in Silverlight. When I add some control to my xaml file
Share
In Brief
Yes there is a difference. The bottom line is that
x:Namecan be used on object elements that do not haveNameproperties of their own.A longer explanation
You can only use
Nameon an element that represents an object that actually does have aNameproperty. For example anything that derives fromFrameworkElement.The
x:Nameattribute may be placed on any element that represents an object regardless of whether that object actually has aNameproperty. If the object does have aNameproperty then the value ofx:Namewill be assigned to it hence you can’t have bothx:NameandNameon the same element.When an object has a
Nameproperty or anx:Nameproperty the value of that property is associated with the objects entry in the object tree. It is via the object tree that theFindNamemethod of aFrameworkElementcan find an object.FindNamecan find objects by name even if that object does not carry aNameproperty of its own since it uses the name recorded in the object tree.The autogenerated code for a
UserControlwill contain field definitions for any element that that has aNameorx:Nameproperty. TheInitialiseComponentmethod that is generated will use theFindNamemethod to assign values to these fields.Example
The above Xaml creates two fields
LayoutRootof typeGridandMyBrushof typeSolidColorBrush. If you were to changex:Name="LayoutRoot"toName="LayoutRoot"that would change nothing.Gridhas aNameproperty. However try changingx:Name="MyBrush"toName="MyBrush". That doesn’t work becauseSolidColorBrushdoesn’t have a name property. With the above Xaml you can then do code like this:-Open the definition of
InitializeComponentand take a look at the auto generated code.