
This topic introduces the concept of markup extensions for Extensible Application Markup Language (XAML), including their syntax rules, purpose, and the class object model that underlies them. Markup extensions are a general feature of the XAML language and of the .NET implementation of XAML services. This topic specifically details markup extensions for use in WPF XAML.
This topic contains the following sections.
- XAML Processors and Markup Extensions
- Basic Markup Extension Syntax
- XAML-Defined Markup Extensions
- WPF-Specific Markup Extensions
- *Extension Classes
- Escape Sequences and Markup Extensions
- Nesting Markup Extensions in XAML Usage
- Markup Extensions and Property Element Syntax
- Related Topics
Generally speaking, a XAML parser can either interpret an attribute value as a literal string that can be converted to a primitive, or convert it to an object by some means. One such means is by referencing a type converter; this is documented in the topic TypeConverters and XAML. However, there are scenarios where different behavior is required. For example, a XAML processor can be instructed that a value of an attribute should not result in a new object in the object graph. Instead, the attribute should result in an object graph that makes a reference to an already constructed object in another part of the graph, or a static object. Another scenario is that a XAML processor can be instructed to use a syntax that provides non-default arguments to the constructor of an object. These are the types of scenarios where a markup extensions can provide the solution.
A markup extension can be implemented to provide values for properties in an attribute usage, properties in a property element usage, or both.
When used to provide an attribute value, the syntax that distinguishes a markup extension to a XAML processor is the presence of the opening and closing curly braces ({ and }). The type of markup extension is then identified by the string token immediately following the opening curly brace.
When used in property element syntax, a markup extension is visually the same as any other element used to provide a property element value: a XAML element declaration that references the markup extension class as an element, enclosed within angle brackets (<>).
Several markup extensions exist that are not specific to WPF application of XAML, but are instead implementations for features of XAML as a language. These markup extensions are defined in the System.Xaml assembly as part of the general .NET XAML services. In terms of common markup usage, these markup extensions are typically identifiable by the x: prefix in the usage. The MarkupExtension base class (also defined in System.Xaml) provides the pattern that all markup extensions should use in order to be supported in the .NET XAML readers and XAML writers, including in WPF XAML.
x:Type supplies the Type object for the named type. This is used most frequently in styles and templates. For details, see x:Type Markup Extension.
x:Static produces static values from value-type code entities that are not directly the type of a property's value, but can be evaluated to that type. For details, see x:Static Markup Extension.
x:Null specifies null as a value for a XAML property and can be used either for attributes or property element values. For details, see x:Null Markup Extension.
x:Array provides support for creation of general arrays in XAML syntax, for cases where the collection support provided by WPF base elements and control models is deliberately not used. For details, see x:Array Markup Extension.
Note |
|---|
The x: prefix is used for the typical XAML namespace mapping of the XAML namespace, in the root element of a XAML file or document. For example, the Visual Studio templates for WPF applications initiate a XAML file using this x: mapping. You could choose a different prefix token in your own XAML namespace mapping, but this documentation will assume the default x: mapping as a means of identifying those entities that are a defined part of the XAML namespace, as opposed to the WPF namespace or other XAML namespaces not related to a specific framework implementation's intended default. |
The most common markup extensions used in WPF programming are those that support resource references (StaticResource and DynamicResource), and those that support data binding (Binding).
StaticResource provides a value for a XAML property by substituting the value of an already defined resource. A StaticResource evaluation is ultimately made at XAML load time and does not have access to the object graph during actual run time. For details, see StaticResource Markup Extension.
DynamicResource provides a value for a XAML property by deferring that value to be a run-time reference to a resource. A dynamic resource reference forces a new lookup each time that such a resource is accessed and has access to the object graph at run time. In order to get this access, DynamicResource concept is supported by dependency properties in the WPF property system, and evaluated expressions. Therefore you cannot use DynamicResource for all possible properties in WPF. For details, see DynamicResource Markup Extension.
Binding provides a data bound value for a property, per the data context that applies to the element. This markup extension is relatively complex, because it enables a substantial inline syntax for specifying a data binding. For details, see Binding Markup Extension.
RelativeSource provides source information for a Binding that can navigate several possible relationships in the run-time element tree. This provides specialized sourcing for bindings that are created in multi-use templates or created in code without full knowledge of the surrounding element tree. For details, see RelativeSource MarkupExtension.
TemplateBinding enables a control template to use values for templated properties that come from object-model-defined properties of the class that will use the template. For details, see TemplateBinding Markup Extension. For more information on the practical use of TemplateBinding, see Styling with ControlTemplates Sample.
ColorConvertedBitmap supports a relatively advanced imaging scenario. For details, see ColorConvertedBitmap Markup Extension.
ComponentResourceKey and ThemeDictionary support aspects of resource lookup, particularly for resources and themes that are packaged with custom controls. For more information, see ComponentResourceKey Markup Extension, ThemeDictionary Markup Extension, or Control Authoring Overview.
For both the general CLR XAML and WPF-specific markup extensions, the behavior of each markup extension is identified to a XAML processor through a *Extension class that derives from MarkupExtension, and provides an implementation of the ProvideValue method. This method on each extension defines what object is returned once the markup extension is evaluated. The returned object is typically instantiated or set by using the various string tokens passed to the markup extension.
For example, the StaticResourceExtension class provides the surface implementation of actual resource lookup so that its ProvideValue implementation returns the object that is requested, with the input of that particular implementation being a string that is used to look up the resource by its x:Key. Much of this implementation detail is unimportant if you are using an existing markup extension.
The *Extension naming pattern is for convenience and consistency. It is not necessary in order for a XAML processor to identify that class as support for a markup extension. So long as your codebase includes System.Xaml and uses CLR XAML services implementation, all that is necessary to be recognized as a XAML markup extension is to derive from MarkupExtension and support a construction syntax. WPF defines markup extension-enabling classes that do not follow the *Extension naming pattern, for example Binding .
Extension Class Interpretation of Initialization Text
The string tokens following the markup extension identifier and still within the braces are interpreted by a XAML processor in one of the following ways:
A comma always represents the separator or delimiter of individual tokens. Therefore a literal comma cannot be passed to a markup extension without escapement.
If the individual separated tokens do not contain any equals signs, each token is treated as a constructor argument. Each constructor parameter must be given as the type expected by that signature, and in the proper order expected by that signature.
NoteA XAML processor must call the constructor that matches the argument count of the number of pairs. For this reason, if you are implementing a custom markup extension, do not provide multiple parameters with the same argument count. The behavior for how a XAML processor behaves if more than one markup extension constructor path with the same parameter count exists is not defined.
If the individual separated tokens contain equals signs, then a XAML processor first calls the default constructor for the markup extension. Then, each name=value pair is interpreted as a property name that exists on the markup extension, and a value to assign to that property.
If there is a parallel result between the constructor behavior and the property setting behavior in a markup extension, it does not matter which behavior you use. It is more common usage to use the property=value pairs for markup extensions that have more than one settable property, if only because it makes your markup more intentional and you are less likely to accidentally transpose constructor parameters (when you specify property=value pairs, those properties may be in any order). Also, there is no guarantee that a markup extension supplies a constructor parameter that sets every one of its settable properties. For instance, Binding is a markup extension, with many properties that are settable through the extension in property=value form, but Binding only supports two constructors: a default constructor, and one that sets an initial path.
Attribute handling in a XAML processor uses the curly braces as indicators of a markup extension. It is also possible to produce a literal curly brace character attribute value if necessary, by entering an escape sequence using an empty curly brace pair followed by the literal curly brace. See {} Escape Sequence / Markup Extension.
Nesting of multiple markup extensions is supported, and each markup extension will be evaluated deepest first, for instance:
<Setter Property="Background"
Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
When used as an object element that fills a property element value, a markup extension class is visually indistinguishable from an ordinary element that can be used in XAML. The practical difference between an ordinary element and a markup extension in this circumstance is that the markup extension is either evaluated to a typed value or deferred as an expression, and therefore the mechanisms for any possible type errors of property values will be different, similar to how a late-bound property is treated in other programming models. An ordinary element will be evaluated for type versus the property it is setting immediately on compilation.
Most markup extensions, when used in object element syntax to fill a property element, would not have content or any further property element syntax within, and thus you would close the object element tag, and provide no child elements. Whenever any object element is encountered by a XAML processor, the constructor for that class is called to instantiate the object created from the parsed element. A markup extension class is no different; therefore, if you want your markup extension to be usable in object element syntax, you must provide a default constructor. Some existing markup extensions have at least one required property value that must be specified for effective initialization, and if so, that property value is typically given as a property attribute on the object element. In the XAML Namespace (x:) Language Features and WPF XAML Extensions reference pages, markup extensions that have required properties (and the names of required properties) will be noted. Reference pages will also note if either object element syntax or attribute syntax is disallowed for particular markup extensions. A notable case is x:Array Markup Extension, which cannot support attribute syntax because the contents of that array must be specified. The array contents are handled as general objects, therefore no default type converter for the attribute is feasible. Also, x:Array Markup Extension requires a Type parameter.
