What is the Difference Between x:Key, x:Name, and

2019-03-22 16:36发布

问题:

I am trying to create dynamic tabs in WPF, and I'm trying to write a content template that will only apply to some tab items. I want to be able to create an identifier for the content template so that I can reference it in the code behind, and so that I can selectively apply it to only some tabs in a single TabControl. However, I am confused about these three different xaml identifiers. What is the difference, and which one is best for my purposes?

回答1:

The 'x:' specifies the namespace, which would in your case most likely be "http://schemas.microsoft.com/winfx/2006/xaml" You will see the alias declared at the top of your Window.Xaml file. x:Key, x:Name, etc are all directives in that namespace.

In contrast, the 'Name' attribute (without the x:) is a dependency property declared in the FrameworkElement class.

x:Key

Uniquely identifies elements that are created and referenced in a XAML-defined dictionary. Adding an x:Key value to a XAML object element is the most common way to identify a resource in a resource dictionary, for example in a WPF ResourceDictionary.

x:Name

Uniquely identifies XAML-defined elements in a XAML namescope. XAML namescopes and their uniqueness models can be applied to the instantiated objects, when frameworks provide APIs or implement behaviors that access the XAML-created object graph at run time.

x:Uid

Provides a unique identifier for markup elements. In many scenarios, this unique identifier is used by XAML localization processes and tools.

Notes

I have only seen x:Uid when a app must support different languages with a resource dictionary.

For the other two (x:Key and x:Name), a basic rule of thumb is to use x:Name for Framework elements and x:Key for styles, templates, and so on. So for your question, if you are naming a template itself, you would use the x:Key directive. Controls declared within the template would use the x:Name directive.

A complete list of all Xaml directives is given at Xaml Namespace



回答2:

If you want to apply the template to all the tabs in your page, you can use x:Type, but if you want to apply it to few tabs and not to all the tabs you can use x:Key.

Generally you will use x:Key when you want to use it as StaticResource in your xaml file. You will provide x:Name to a control or template when you want to refer it in your code-behind. I have never used X:Uid, but this is what MSDN says,

Use x:Uid to identify an object element in your XAML. Typically this object element is an instance of a control class or other element that is displayed in a UI. The relationship between the string you use in x:Uid and the strings you use in a resources file is that the resource file strings are the x:Uid followed by a dot (.) and then by the name of a specific property of the element that's being localized.