Take the 2-minute tour ×

What's the difference between x:Key and x:Name in WPF?

Not sure what the true difference is.

share|improve this question
@Alastair, the question you listed as a possible dupe is unrelated to this. –  Josh Dec 13 '10 at 3:39
how is it a duplicate? The other question talks about Name vs Type. This question is about Key vs Name. –  jalf Dec 13 '10 at 3:40
My mistake, I misread the "possible dupe" question. Apologies. –  Alastair Pitts Dec 13 '10 at 3:51

2 Answers 2

up vote 28 down vote accepted

Although they are used for similar purposes, they are not interchangeable. x:Key is used for items that are being added as values to a dictionary, most often for styles and other resources that are being added to a ResourceDictionary. When setting the x:Key attribute, there is actually no corresponding property on the object or even an attached dependency property being set. It is simply used by the XAML processor to know what key to use when calling Dictionary.Add.

x:Name is a bit more complicated. It's used to apply an associated name to an object (typically an object derived from FrameworkElement) within the scope of some parent element. This scope is called a "namescope" and the easiest way to think of it is to imagine a UserControl that contains a <TextBox x:Name="foo" />.

You could then put multiple instances of the UserControl onto a Window without the name "foo" colliding because each UserControl has its own namescope.

It's worth noting too that FrameworkElement defines a dependency property called Name that is equivalent to setting x:Name.

The other difference is that the XAML designer creates members in the code-behind for elements that have an x:Name. This is not true of objects added to a dictionary using x:Key.

You can find more information about these in the remarks section of the MSDN documentation for the x:Name directive.

share|improve this answer

x:Key is only valid in the scope of a ResourceDictionary element. x:Key is used as the primary identifier for elements in the ResourceDictionary.

On the other hand, x:Name is valid in the scope of everything but a ResourceDictionary. x:Key is not valid outside the ResourceDictionary scope.

share|improve this answer

Your Answer


