Is there any difference in x:name and name for controls in xaml file?

In Brief

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.

A longer explanation

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.

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.

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.

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.

Example

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;
    }

Open the definition of InitializeComponent and take a look at the auto generated code.

Leave a Comment