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

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

I'm not sure what the true difference is.

+45
wpf
Dec 13 '10 at 3:23
source share
2 answers

Although they are used for similar purposes, they are not interchangeable. x: The key is used for elements that are added as values ​​to the dictionary, most often for styles and other resources that are added to the ResourceDictionary. When setting the x: Key attribute on the object, the corresponding property or even the set dependency property is actually missing. It is simply used by the XAML processor to find out which key to use when calling Dictionary.Add.

x: The name is a little more complicated. He used to bind the associated name to an object (usually to an object derived from FrameworkElement) within some parent element. This area is called "namescope", and the easiest way to think is to imagine a UserControl that contains <TextBox x:Name="foo" /> .

Then you can put multiple instances of UserControl in the window without clashing the name "foo", because each UserControl has its own clearness.

It is also worth noting that FrameworkElement defines a Name dependency property, which is equivalent to setting x: Name.

Another difference is that the XAML constructor creates elements in the code for elements that have x: Name. This does not apply to objects added to the dictionary using x: Key.

You can find more information on this in the notes section of the MSDN documentation for the x: Name directive .

+42
Dec 13 2018-10-12T00:
source share

x: The key is valid only in the area of ​​the ResourceDictionary element. x: The key is used as the primary identifier for the elements in the ResourceDictionary.

X: Name, on the other hand, is valid in the scope of everything except ResourceDictionary. x: The key is not valid outside the scope of the ResourceDictionary.

+19
Dec 13 2018-10-12T00:
source share



All Articles