× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

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

Gayot Fow
Feb 05, 2015
<p>The 'x:' specifies the namespace, which would in your case most likely be "<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>" 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. </p> <p>In contrast, the 'Name' attribute (without the x:) is a dependency property declared in the FrameworkElement class.</p> <p><strong>x:Key</strong></p> <p>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.</p> <p><strong>x:Name</strong></p> <p>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.</p> <p><strong>x:Uid</strong></p> <p>Provides a unique identifier for markup elements. In many scenarios, this unique identifier is used by XAML localization processes and tools.</p> <p><strong>Notes</strong></p> <p>I have only seen <strong>x:Uid</strong> when a app must support different languages with a resource dictionary.</p> <p>For the other two (x:Key and x:Name), a basic rule of thumb is to use <strong>x:Name</strong> for Framework elements and <strong>x:Key</strong> for styles, templates, and so on. So for your question, if you are naming a template itself, you would use the <strong>x:Key</strong> directive. Controls declared within the template would use the <strong>x:Name</strong> directive.</p> <p>A complete list of all Xaml directives is given at <a href="http://msdn.microsoft.com/en-us/library/ms753327%28v=vs.110%29.aspx">Xaml Namespace</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23935688/What%20is%20the%20Difference%20Between%20x:Key,%20x:Name,%20and%20x:UID%20in%20a%20DataTemplate%20in%20WPF?/23936061">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus