x:Key attribute

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Uniquely identifies elements that are created and referenced as resources, and which exist within a ResourceDictionary.

XAML attribute usage

<ResourceDictionary>
  <object x:Key="stringKeyValue".../>
</ResourceDictionary>

XAML attribute usage (implicit ResourceDictionary)

<object.Resources>
  <object x:Key="stringKeyValue".../>
</object.Resources>

XAML values

Term Description

object

Any object that is shareable. See ResourceDictionary and XAML resource references.

stringKeyValue

A true string used as a key, which must conform to the XamlName grammar. See "XamlName grammar" below.

 

XamlName grammar

The following is the normative grammar for a string that is used as a key in the Windows Runtime XAML implementation:

XamlName ::= NameStartChar (NameChar)*
NameStartChar ::= LetterCharacter | '_'
NameChar ::= NameStartChar | DecimalDigit
LetterCharacter ::= ('a'-'z') | ('A'–'Z')
DecimalDigit ::= '0'-'9'
CombiningCharacter::= none
  • Characters are restricted to the lower ASCII range, and more specifically to Roman alphabet uppercase and lowercase letters, digits, and the underscore (_) character.
  • The Unicode character range is not supported.
  • A name cannot begin with a digit.

Remarks

Child elements of a ResourceDictionary generally include an x:Key attribute that specifies a unique key value within that dictionary. Key uniqueness is enforced at load time by the XAML processor. Non-unique x:Key values will result in XAML parse exceptions. If requested by StaticResource, a non-resolved key will also result in XAML parse exceptions.

x:Key and x:Name are not identical concepts. x:Key is used exclusively in resource dictionaries. x:Name is used for all areas of XAML. A FindName call using a key value will not retrieve a keyed resource.

Note that in the implicit syntax shown, the ResourceDictionary object is implicit in how the XAML processor produces a new object to populate a Resources collection.

The code equivalent of specifying x:Key is any operation that uses a key with the underlying ResourceDictionary. For example, an x:Key applied in markup for a resource is equivalent to the value of the key parameter of Insert when you add the resource to a ResourceDictionary.

An item in a resource dictionary can omit a value for x:Key if it is a targeted Style or ControlTemplate; in each of these cases the implicit key of the resource item is the TargetType value interpreted as a string. For more info, see Quickstart: styling controls and ResourceDictionary and XAML resource references.

ResourceDictionary and XAML resource references

x:Name attribute

XAML overview