4

I have the following UserControl declaration in xaml done by someone else:

<core:UserControlBase x:Class="xxxx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:core="clr-namespace:Agn.Word.AddIn.Core.Presentation;assembly=Agn.Word.AddIn.Core" 

             x:Name="aName">

As far as I know the x:Name attribute is used to give a name to the variable declarer in xaml to be able to reference it from code or from the xaml itself.

Given that this is the root element I don't get why would I use this name for (in code behind I will use this, in xaml I can use RelativeSource, etc).

Any hints?

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207
  • 2
    Sometimes `RelativeSource` is not reliable and you must use element name. – Sinatr Jan 14 '16 at 10:34
  • So you mean that the only reason to have such declaration is to point to the root element using that name from the xaml itself. So if it is not used can I remove completely the declaration? – Ignacio Soler Garcia Jan 14 '16 at 10:36
  • If it's not used in xaml/cs of **this** `UserControl` then it's safe to remove it. *Someone else* may forgot to delete `x:Name` (probably was using it, but then changes something, probably switched to `RelativeSource` or wrote attached behavior instead of code-behind, etc.). – Sinatr Jan 14 '16 at 10:40
  • 1
    [Here](http://stackoverflow.com/a/8146881/1997232) is an example of case when you can't use `RelativeSource` (and `x:Name` works perfectly). – Sinatr Jan 14 '16 at 10:48

1 Answers1

3

You would use x:Name when you want a direct reference to the object:

Uniquely identifies object elements for access to the instantiated object from code-behind or general code. Once applied to a backing programming model, x:Name can be considered equivalent to the variable holding an object reference, as returned by a constructor.

(...)

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.

This is more efficient than using RelativeSource and also creates the variable in the code-behind.

In your example, if you rather not use RelativeSource to navigate the hierarchy and you also don't consume it in the code-behind, you could simply remove it.

jnovo
  • 5,659
  • 2
  • 38
  • 56
  • 3
    It's worth mentioning that `RelativeSource` uses reflection to get the object, and referencing the object by `x:Name` is much faster as the variable is in code-behind. – Mike Eason Jan 14 '16 at 10:42