Summary
x:Name
and AutomationProperties.Name
are two totally different things, so the question "should I use one or the other" is based on a false premise: in general, you cannot use one or the other.
The purpose of x:Name
is to identify a WPF control in code-behind so that the developer can access it. It is not meaningful (or unique) outside the scope of the class that models a specific WPF element.
On the other hand, the purpose of AutomationProperties.Name
is to identify a user interface element in the context of a dialog or other type of window that is presented to the user for interaction. Specifically, its value should match what a user would perceive as the "label" of that user interface element (so that e.g. an accessibility tool can inform the user of the purpose of the element).
While any tool (such as a XAML compiler) can choose to use the value of x:Name
for AutomationProperties.Name
as well doesn't mean that it's something you should do; IMHO this is exactly the type of "convenience" that results in problems because the difference between the two is hidden from the developer, so invariably one or the other property would end up having a semantically wrong value.
Information on the semantic and technical aspects of each of the property follows in the next sections.
x:Name
The MSDN documentation page explains that
After x:Name is applied to a framework's backing programming model,
the name is equivalent to the variable that holds an object reference
or an instance as returned by a constructor.
The value of an x:Name directive usage must be unique within a XAML
namescope.
[...]
Under the standard build configuration for a WPF application that uses
XAML, partial classes, and code-behind, the specified x:Name becomes
the name of a field that is created in the underlying code when XAML
is processed by a markup compilation build task, and that field holds
a reference to the object.
From the above we can tell that x:Name
:
- is used to access the element in code (not XAML), since it controls the name of the field that holds the element
- must be unique within a XAML namescope (since you cannot have two fields with the same name in code)
AutomationProperties.Name
The WPF accessibility documentation explains that
The Name for an automation element is assigned by the developer. The
Name property should always be consistent with the label text on
screen. For example, the Name must be “Browse…” for the button element
with “Browse…” as the label.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…