[WPF Series] – XAML syntax specification

[WPF Series]-XAML syntax specification

Article directory

  • [WPF Series] – XAML syntax specification
    • I. Overview
    • 2. Object element syntax
    • 3. Characteristic syntax (attributes)
    • 4. Processing of characteristic values
    • 5. Enumerated characteristic values
    • 6. Attribute and event member name references
    • 7. Attribute element syntax
    • 8. Set Grammar
    • 9. XAML content attributes
      • XAML content attribute values must be contiguous
    • 10. Content attributes and collection syntax combination
    • 11. Summary

1. Overview

Defined XAML syntax terms are defined or referenced in the XAML language specification. XAML is an XML-based language that follows or extends XML structural rules. XAML is based on the terminology commonly used when describing the XML language or XML Document Object Model.

XAML is a markup language. CLR is an implementable runtime language. XAML is not part of the CRL implementation. It is just an expression that is instantiated and run when used in WPF’s XAML.

2. Object element syntax

Object element syntax is a XAML markup syntax for declaring XML elements to instantiate a CLR class or structure. This syntax is similar to the element syntax of other markup languages, such as HTML. Object element syntax begins with a left angle bracket (<), followed by the type name of the class or structure being instantiated. Zero or more spaces may follow the type name, and zero or more properties may be declared on the object element, using one or more spaces to separate each property name="value" pair. Object elements must meet one of the following conditions:

  • Elements and tags must end with a forward slash (/), followed by a right angle bracket (>).
  • The opening tag must end with a right angle bracket (>). Other object elements, attribute elements, or internal text can follow the start tag. The exact content that may be included here is usually constrained by the element’s object model. An equivalent closing tag for the object element must also be present, properly nested and balanced with other pairs of opening and closing tags.

Example 1:

<TextBox Text="TextBox" Width="120"/>

Example 2:

<TextBox Text="TextBox" Width="120"></TextBox>

3. Attribute syntax (attributes)

Attribute syntax is a XAML markup syntax that sets the value of a property by declaring an attribute on an existing object element. The attribute name must match the CLR member name of the attribute of the class that supports the related object element. The attribute name is followed by the assignment operator (=). The attribute value must be a string enclosed in quotes.

To be set via attribute syntax, the property must be public and must be writable. The value of a property in the backing type system must be a value type, or it must be a reference type that can be instantiated or referenced by the XAML processor when the associated backing type is accessed.

For WPF XAML events, the event referenced as an attribute name must be public and have a public delegate.

4. Processing of characteristic values

String values enclosed in left and right quotes are processed by the XAML processor. For properties, the default processing behavior is determined by the type of the underlying CLR property.

Property values are populated with one of the following, in this processing order:

  1. If the XAML processor encounters a brace or an object element derived from MarkupExtension, the referenced markup extension is evaluated first, and rather than processing the value as a string, the object returned by the markup extension is used as the value. In many cases, the object returned by markup expansion will be a reference to an existing object, or an expression that defers evaluation until runtime, rather than a newly instantiated object.
  2. If a property is declared using an attributed TypeConverter, or the property’s value type is declared using an attributed TypeConverter, the attribute’s string value is submitted as conversion input to the type converter, which returns a new object instance.
  3. If there is no TypeConverter, an attempt is made to convert directly to the property type. This ends up doing a direct conversion of parser native values between XAML language primitive types, or checking the name of a named constant in an enumeration (the parser then accesses the matching value).

5. Enumerated attribute values

Enumerations in XAML are handled internally by the XAML parser, and the members of the enumeration should be specified by specifying the string name of one of the enumeration’s named constants. For non-flag enumeration values, the native behavior is to process the string of attribute values and parse it into one of the enumeration values. There is no need to specify the enumeration in the format “enum.value” as you would in code. Instead, you only specify the value, which the enumeration infers from the type of property being set. If the attribute is specified in the form “enum.value”, it will not be parsed correctly.

For enumeration by flag, the behavior is based on the Enum.Parse method. You can specify multiple values for a by-flag enumeration by separating each value with a comma. However, enumeration values that are not flagged cannot be merged.

6. Attribute and event member name references

When specifying a property, you can reference any property or event that exists as a member of the CLR type that contains the object element instantiated. Or you can reference attached properties or attachment events that are independent of the containing object element.

Use the typeName.event partially qualified name to name any event in any object accessible through the default namespace; this syntax supports attaching handlers for routed events, where the handler is intended to handle events routed from child elements, but not parent elements It also does not contain the event in its members table. This syntax is similar to the attached event syntax, but the events here are not really attached events. Instead, refer to the event using a qualified name.

7. Attribute element syntax

Attribute element syntax is a syntax that differs somewhat from the basic XML syntax rules for elements. In XML, the value of an attribute is actually a string, and the only possible variation is the string encoding format used. In XAML, you can assign other object elements as the value of a property. The attribute element syntax enables this feature by default. Rather than being specified as attributes in element tags, properties are specified in the form elementTypeName.propertyName, using an opening element tag, in which the value of the property is specified, and then the closing property element. Specifically, the syntax begins with a left angle bracket (<), followed by the type name of the class or structure within which the attribute element syntax is contained. It is followed by a single dot (.), then the name of the attribute, and then the right angle bracket (>). As with attribute syntax, the property must exist in a declared public member of the specified type.

Attribute element syntax example:

<Button>
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="1">First item</MenuItem>
      <MenuItem Header="2">Second item</MenuItem>
    </ContextMenu>
  </Button.ContextMenu>
  Right-click me!
</Button>

8. Set syntax

The XAML specification requires that XAML processors implement properties that identify value types that are collections. The regular XAML processor implementation in .NET is based on managed code and the CLR, and identifies collection types through one of the following methods:

  • Type implements IList
  • Type implements IDictionary
  • Type derived from Array

If the attribute’s type is a collection, the inferred collection type does not need to be specified in the markup as an object element. Instead, elements intended to be items in a collection are specified as one or more child elements of the attribute element.

<Style x:Key="SpecialButton" TargetType="{x:Type Button}">
  <Style.Triggers>
    <Trigger Property="Button.IsMouseOver" Value="true">
      <Setter Property = "Background" Value="Red"/>
    </Trigger>
    <Trigger Property="Button.IsPressed" Value="true">
      <Setter Property = "Foreground" Value="Green"/>
    </Trigger>
  </Style.Triggers>
</Style>

9. XAML content attributes

XAML content syntax is a syntax that is only enabled on classes that specify a ContentPropertyAttribute as part of the class declaration. ContentPropertyAttribute refers to the property name that is the content attribute of elements of that type (including derived classes). When processed by a XAML processor, any child elements or inner text found between the opening and closing tags of an object element are assigned the value of the object’s XAML content attribute. Specifying explicit attribute elements for content properties is allowed, but this usage does not typically appear in the XAML syntax section of the .NET reference. Explicit/verbose techniques are occasionally valuable for making markup clear or in terms of markup styling, but the intent of the content attribute is usually to simplify markup so that elements that are intuitively related in a parent-child fashion can be directly nested. According to the strict XAML language definition, attribute element tags for other properties on an element are not assigned as “content”; they were previously processed in the order in which the XAML parser is processed and are not considered “content”.

  • XAML content attribute values must be consecutive

The value of an AML content attribute must be specified completely before or after any other attribute elements of the object element. This is true regardless of whether the value of the XAML content attribute is specified as a string or one or more objects. For example, the following tags will not be analyzed:

<Button Margin="67,45,202,245">
    <Button.Background>Blue</Button.Background>
    <Button.FontSize>Bold</Button.FontSize>
    <Button.Foreground>#FFFFF5F5</Button.Foreground>
    <Button.Content>This is a button with a background</Button.Content>
</Button>

10. Content attributes and collection syntax combination

To accept multiple object elements as content, the type of the content attribute must be explicitly a collection type. Similar to the property element syntax for collection types, the XAML processor must identify types that belong to the collection type. If an element has a XAML content attribute, and the XAML content attribute’s type is a collection, the implicit collection type does not need to be specified in the markup as an object element, and the XAML content attribute does not need to be specified as a property element. Therefore, the explicit content model in markup can now assign multiple child elements as content.

<Window x:Class="_010_WPF_Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_010_WPF_Demo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="900">
    <Grid>
        <StackPanel Width="100" Height="200">
            <Button>Button 1</Button>
            <Button>Button 2</Button>
            <Button>Button 3</Button>
        </StackPanel>

    </Grid>
</Window>

11. Summary

XAML syntax specifications generally include the above commonly used methods. In actual applications, appropriate method combinations will be selected to complete application development based on different scenarios.