다음을 통해 공유


x:Key Attribute

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

XAML Attribute Usage

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

XAML Values

StringKeyValue

A true string used as a key, which must conform to the XAMLName Grammar.

- or -

A markup extension that supplies an alternative object type that serves as a key. See Remarks.

Remarks

Child elements of a parent element that is a IDictionary implementation such as ResourceDictionary generally must include an x:Key attribute that specifies a unique key value within that dictionary. The exceptions are a Style with a TargetType, or a DataTemplate with a DataType, each of which already has an implicit key. Key uniqueness is enforced at load time by the WPF XAML reader implementation. Missing and/or non-unique x:Key values will result in load-time errors.

The attribute value of x:Key can be any string defined in the XAMLName Grammar or can be an object evaluated through a markup extension. For instance, the value of x:Key may be a ComponentResourceKey. The scenario here is used when certain controls expose a style key that can be used to create a custom style resource that influences the look and feel of that control without totally replacing the style. An example of such a key is ButtonStyleKey.

Note that in the syntax shown, the ResourceDictionary object is implicit in how the XAML reader produces a collection to populate a Resources collection, and is not typically provided explicitly as an element in markup, although it can be if desired for clarity (it would be a collection object element between the Resources property element and the items within that populate the dictionary). For details on why a collection object is an implicit element in markup, see XAML Syntax Terminology.

In the WPF XAML reader implementation, the handling for this markup extension is defined by the ResourceKey abstract class. However the WPF XAML reader produces different underlying extension types for keys based on their usages. For instance, the key for a DataTemplate or derived classes is handled separately and produces a distinct DataTemplateKey object.

Keys and names are not identical concepts, and in fact are mutually exclusive by the WPF definition of these concepts. For details, see WPF Namescopes.

The code equivalent of specifying x:Key is the key as used for any operation that uses a key with the underlying IDictionary. For instance, an x:Key applied in markup for a resource is equivalent to the value of the key parameter of ResourceDictionary.Add when you add the resource to a ResourceDictionary. (x:Key is a XAML language feature, and is not exclusively intended for ResourceDictionary, but that is the most frequent application of x:Key in the WPF XAML implementation).

See Also

Reference

StaticResource Markup Extension

Concepts

Resources Overview
Resources and Code