What is the Difference Between x:Key, x:Name, and x:UID in a DataTemplate in WPF?

前端 未结 2 690
后悔当初
后悔当初 2021-02-03 21:16

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

2条回答
  •  情歌与酒
    2021-02-03 21:34

    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

提交回复
热议问题