Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Silverlight 3
XAML
 XAML Overview
Collapse All/Expand All Collapse All
Silverlight
XAML Overview

This overview describes the different ways to declare objects and set properties in Extensible Application Markup Language (XAML) as used with Silverlight.

This topic contains the following sections.

Extensible Application Markup Language (XAML) is a declarative language. You can create visible user interface (UI) elements in the declarative XAML markup. You can then use a separate code-behind file to respond to events and manipulate the objects you declared in XAML. An XML-based declarative language is very intuitive for creating interfaces from prototype to production, especially for people with a background in Web design and technologies.

XAML files are XML files that generally have the .xaml file name extension. The following example shows the contents of a very basic Silverlight XAML file.

XAML
<UserControl x:Class="MySilverlight.Page"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
>
  <Grid Background="OldLace">
  </Grid>
</UserControl>

XAML as a language is case-sensitive. This is another consequence of XAML being based on XML, which is also case-sensitive per the XML language definitions. The names of XAML elements and attributes are case-sensitive. The value of an attribute is potentially case-sensitive; this will depend on how the attribute value is handled for particular properties. For example, if the attribute value declares an enumeration member name, the built-in behavior that type-converts a member name string to return the enumeration member value is not case-sensitive. In contrast, the value of the Name property, as well as utility methods for working with objects based on the name that the Name property declares, treat the name string as case-sensitive.

There are two ways to declare objects in XAML:

  • Directly, using object element syntax: Uses opening and closing tags to declare an object as an XML element. You can use this syntax to declare root objects or to set property values.

  • Indirectly, using attribute syntax: Uses an inline value to declare an object. You can use this syntax to set the value of a property. This is an indirect operation for the XAML processor, because there must be something behind the scenes that knows how to create a new object on basis of knowing what property is being set, and the supplied string value. Typically, this means that the type or property in question supports a type converter that can work with string input.

This does not mean that you always have the choice of using either object element syntax or attribute syntax. Certain objects can be created only by using object element syntax. A small number of objects can be created only by being initially set to a property value. Objects that can be created with either object element or attribute syntax are comparatively rare in Silverlight.

In addition to declaring an object, there are also techniques you can use in XAML to reference existing objects. This is discussed in detail in the Markup Extensions section of this topic.

Declaring an Object by Using Object Element Syntax

To declare an object with object element syntax, you write the following two element tags, where objectName is the name of the object that you want to instantiate. In this documentation, you will often see the term object element, which is shorthand for the particular markup that is used to create a XAML object in object element syntax.

<objectName>

</objectName>

The following example uses object element syntax to declare a Canvas object.

XAML
<Canvas>
</Canvas>

Some objects, such as Canvas, can contain other objects.

XAML
<Canvas>
  <Rectangle>
  </Rectangle>
</Canvas>

As a convenience (and as part of the general XAML relationship to XML), if the object does not contain other objects, you can declare the object element by using one self-closed tag instead of an opening/closing pair, as shown by the <Rectangle /> tag in the following example.

XAML
<Canvas>
  <Rectangle />
</Canvas>

Declaring an Object by Using Attribute Syntax

In some cases where the value of a property is not just a language primitive such as a string, you can use attribute syntax to both instantiate the object type that sets the property and to set key properties that define the new object. Because this behavior is tied to property setting, see the following sections for information about how attribute syntax can used to declare an object and to set its properties in one step.

You can set properties on objects that you declared by using object element syntax. There are multiple ways to set properties in XAML:

  • By using attribute syntax.

  • By using property element syntax.

  • By using content element syntax.

  • By using a collection syntax (which is usually implicit collection syntax).

As with object declaration, this list of techniques does not imply that a given property could be set with any of the techniques. Some properties support only one of the techniques. Some properties might support combinations; for example, a property that supports content element syntax might also support property element syntax or attribute syntax. This depends both on the property and on the object type that the property uses. The possibilities for XAML syntax are provided in the "XAML Usage" sections of reference pages for each property that can be set in XAML. There are also Silverlight properties that cannot be set in XAML by any means, and must instead be set using code.

A read-only property cannot be set by any means, either in XAML or in code, unless there is an additional mechanism in play. This might be calling a constructor overload that sets to the property's internal representation, a method that is not strictly the property accessor, or a property relationship such as a calculated property that relies on the values of other settable properties plus perhaps a service or behavior influence on that property value. Also, collections give an appearance that you are setting a read-only property, but in fact you are not (see Setting a Property by Using a Collection Syntax).

Setting a Property by Using Attribute Syntax

Use the following syntax, where objectName is the object you want to instantiate, propertyName is the name of the property that you want to set on that object, and propertyValue is the value to set.

<objectName propertyName="propertyValue" .../>

-or-

<objectName propertyName="propertyValue">

...<!--element children -->

</objectName>

Either of these syntaxes enable you to declare an object and set a property on that object. Although the first example is a single element in markup, there are actually discrete steps here with regard to how a XAML processor parses this markup. First, the presence of the object element indicates that a new objectName object must be instantiated. Only after such an instance exists can the instance property propertyName can be set on it.

The following example uses attribute syntax for three attributes to set the width, height, and fill properties of a Rectangle object.

XAML
<Rectangle Width="100" Height="100" Fill="Blue" />

Setting a Property by Using Property Element Syntax

Some properties can be set by using property element syntax. To use property element syntax, it must be possible to specify a new instance of an object element in order to "fill" the property element value.

To use property element syntax, you create XML elements for the property that you want to set. These elements are in the form <object.property>. In standard XML, this element would just be considered an element that has a dot in its name. However, in XAML, the dot in the element name identifies the element as a property element, with property being a property of object.

In the following grammar, property is the name of the property that you want to set and propertyValueAsObjectElement is a new object element that declares a new object, which is of the value type that the property expects.

<object>

<object.property>

propertyValueAsObjectElement

</object.property>

</object>

The following example uses property element syntax to set the fill of a Rectangle with a SolidColorBrush object element. (Within the SolidColorBrush, the Color is set by using attribute syntax.) The rendered result of this XAML is identical to the previous XAML example that set Fill using attribute syntax.

XAML
<Rectangle
  Width="100" 
  Height="100"
> 
  <Rectangle.Fill> 
    <SolidColorBrush Color="Blue"/> 
  </Rectangle.Fill>
</Rectangle>

Setting a Property by Using Content Element Syntax

Some Silverlight objects define a property that enables a XAML syntax whereby you can omit the property name and set the property by providing a value within the owning type's object element tags. This is known as content element syntax. If content element syntax is available, the syntax will be shown in the XAML Usage sections of Syntax for the property in the Silverlight reference documentation. For example, the Text property page for TextBlock shows an alternative XAML syntax that uses content element syntax instead of attribute syntax to set the string value of Text.

The following example sets the Text property of a TextBlock without explicitly specifying the Text property. In this case the property is set using what XML would consider to be content or "inner text," rather than using an attribute, or declaring an object element.

XAML
<TextBlock>
  Hello!
</TextBlock>
NoteNote:

Another way to identify which objects support a content property syntax and which property implements it is available through examining the CLR attributes that are applied to the type. This can be done by reflection. Any type that supports content element syntax will have ContentPropertyAttribute applied.

Setting a Property by Using a Collection Syntax

Collections are an interesting case in XAML, because there are several variations of collection syntax. Also, it might at first appear that XAML is letting you "set" read-only collection properties. In reality, what XAML enables here is adding items to a collection.

Something that is always omitted from the XAML collection syntaxes is the property of the collection type that holds the collection items. In many cases, such a property is defined as a CLR indexer. For collections, what is really necessary to do anything useful with a collection from XAML is not a property, but a method: the Add method. Thus, when the XAML processor encounters one or more object elements within a collection syntax, each such object is first created, then each new object is added to the collection by calling the collection's Add method.

The following example shows a collection property that uses a collection type that is constructible (you can define and initialize the actual collection as an object element in XAML).

XAML
<LinearGradientBrush>
  <LinearGradientBrush.GradientStops>
    <!-- Here the GradientStopCollection tag is specified. -->
    <GradientStopCollection>
      <GradientStop Offset="0.0" Color="Red" />
      <GradientStop Offset="1.0" Color="Blue" />
    </GradientStopCollection>
  </LinearGradientBrush.GradientStops>
</LinearGradientBrush>

However, generally for a Silverlight property that takes a collection, the XAML parser implicitly knows the type of the collection, based on the property the collection is contained in. Therefore, you can omit the object element for the collection itself, as shown in the following example.

XAML
<LinearGradientBrush>
  <LinearGradientBrush.GradientStops>
    <!-- no explicit new GradientStopCollection, parser knows how to find or create -->
    <GradientStop Offset="0.0" Color="Red" />
    <GradientStop Offset="1.0" Color="Blue" />
  </LinearGradientBrush.GradientStops>
</LinearGradientBrush>

Also, there are properties that are collection properties but are also identified as the content property for the class. This is the case with the GradientStops property being used in the previous examples. Therefore, you can also omit the property element. This results in the following markup:

XAML
<LinearGradientBrush>
  <GradientStop Offset="0.0" Color="Red" />
  <GradientStop Offset="1.0" Color="Blue" />
</LinearGradientBrush>

This combination of collection and content syntaxes is most frequently seen in the classes that are used extensively for control compositing, such as panels. For instance, the following examples show the explicit XAML and the simplest possible XAML for compositing two UI elements within a StackPanel.

XAML
<!--explicit-->
<StackPanel>
  <StackPanel.Children>
    <!--UIElementCollection-->
    <TextBlock>Hello</TextBlock>
    <TextBlock>World</TextBlock>
    <!--/UIElementCollection-->
  </StackPanel.Children>
</StackPanel>

<!--simple-->
<StackPanel>
  <TextBlock>Hello</TextBlock>
  <TextBlock>World</TextBlock>
</StackPanel>

Notice the commented-out UIElementCollection in the explicit syntax. This is commented out because even though the collection in question will exist in the created object tree, you cannot specify it explicitly in XAML, because UIElementCollection is not a constructible class. There are scenarios for deliberately and explicitly including the collection class in the markup (such as giving the collection an x:Name so that it can be referenced more easily in code). However, be careful to not explicitly declare collection classes that cannot be constructed by the XAML parser because of their class characteristics.

When to Use Attribute or Property Element Syntax to Set a Property

All properties that support being set in XAML will support attribute or property element syntax for direct value setting, but potentially will not support either syntax interchangeably. Some properties do support either syntax, and some properties support additional syntax options such as the content element syntax for Text shown previously. The type of XAML syntax supported by a property partially depends on the type of object that the property uses as its property type. If the property type is a primitive type, such as a double, integer, or string, the property always supports attribute syntax.

The following example uses attribute syntax to set the width of a Rectangle. The Width property supports attribute syntax, because the property value is a double.

XAML
<Rectangle Width="100" />

You can also use attribute syntax to set a property if the object type you use to set that property can be created by type-converting a string. For primitives, this is always the case. However, certain other object types can also be created by using a string specified as an attribute value (instead of requiring object element syntax). This technique uses an underlying type conversion, supported either by that particular property or generally by that property type. The string value of the attribute is parsed, and the string information is used to set properties that are important for the initialization of the new object. Potentially, a specific type converter can also create different subclasses of a common property type, depending on how it uniquely processes information in the string. Object types that support this behavior will have a special grammar listed in the syntax section of the documentation.

The following example uses attribute syntax to set the fill of a Rectangle. The Fill property supports an attribute syntax when you use a SolidColorBrush to set it. This is because the Brush abstract type that backs the Fill property supports a type-converted grammar that can create a SolidColorBrush that is initialized with the attribute-specified string as its Color (for details on this specific example, see Brush and SolidColorBrush).

XAML
<Rectangle Width="100" Height="100" Fill="Blue" />

You can use property element syntax to set a property if the object you use to set that property supports object element syntax. If the object supports object element syntax, the property also supports property element syntax. The following example uses property element syntax to set the fill of a Rectangle. The Fill property supports property element syntax when you use a SolidColorBrush to set it, because SolidColorBrush supports object element syntax and satisfies the property's requirements that its value is set with a type of Brush. (The SolidColorBrush also has its Color property set, using attribute syntax. The rendered result of this XAML is identical to the previous XAML example that set Fill using attribute syntax.)

XAML
<Rectangle Width="100" Height="100">
  <Rectangle.Fill>
    <SolidColorBrush Color="Blue"/>
  </Rectangle.Fill>
</Rectangle>

Because of the Brush type converter, SolidColorBrush is the only Brush case where you can choose either property element syntax or attribute syntax for a new Fill value (without resorting to a resource reference, or binding). For the other Brush types that you can use to set the Fill, there is no type converter behavior available to create that type of Brush. Therefore, if you want to set a Fill by using a brush type such as ImageBrush, you must use the property element syntax for Fill and declare an ImageBrush as an object element to provide the property value, or use a markup extension as is documented in the next section.

XAML
<Rectangle Width="100" Height="100">
  <Rectangle.Fill>
    <ImageBrush ImageSource="forest.jpg"/>
  </Rectangle.Fill>
</Rectangle>

Markup extensions are a XAML language concept, used prominently in the Silverlight XAML implementation. In XAML attribute syntax, braces ({ and }) indicate a markup extension usage, as per the XAML specification. This usage directs the XAML processing to escape from the general treatment of attribute values as either a literal string or a directly string-convertible value. Instead, a parser typically calls code that backs that particular markup extension, which assists in constructing an object tree from the markup.

Silverlight supports three markup extensions that are defined under its XML namespace and understood by its XAML parser. These are: Binding, StaticResource, and TemplateBindingBinding supports data binding. StaticResource supports referencing resources that are defined in a ResourceDictionary. TemplateBinding supports control templates in XAML that can interact with the code properties of the templated object. Silverlight also implements one markup extension that is defined in the XAML namespace, x:Null.

Properties that take a reference-type value (where the type has no converter) require property element syntax (which always creates a new instance) or an object reference through a markup extension. The Silverlight markup extensions generally return an existing instance. By using markup extensions, every property that is settable in XAML is potentially settable in attribute syntax. You can use attribute syntax to provide reference values for a property even if it does not support an attribute syntax for direct object instantiation, or you can enable specific behavior that defers the general requirement that XAML properties be filled by value types or just-in-time created reference types.

For instance, the following example sets the value of the Style property of a Border by using attribute syntax. The Style property takes an instance of the Style class, a reference type that by default could not be created using an attribute syntax string. But in this case, the attribute references a particular markup extension, StaticResource. When that markup extension is processed, it returns a reference to a style that was previously instantiated as a keyed resource in a resource dictionary.

XAML
<Canvas.Resources>
  <Style TargetType="Border" x:Key="PageBackground">
    <Setter Property="BorderBrush" Value="Blue"/>
    <Setter Property="BorderThickness" Value="5"/>
  </Style>
</Canvas.Resources>
...
<Border Style="{StaticResource PageBackground}">
  ...
</Border>

For a reference listing of markup extensions, see Silverlight Namespace Extensions or XAML Namespace (x:) Language Features.

Literal "{" Values

Because the opening brace symbol { is the opening of the markup extension sequence, you must use an escape sequence in order to specify a literal string value that starts with {. The escape sequence is {}. For example, to specify a string value that is a single opening brace, specify the attribute value as {}{. You can also use the alternative quotation marks (for example, a ' within an attribute value delimited by "") in some cases to provide a { value as a string.

XAML is a declarative language for objects and their properties, but it also includes a syntax for attaching event handlers to objects in the markup. You specify the name of the event as an attribute name on the object where the event is handled. For the attribute value, you specify the name of an event-handler function that you define in code. The XAML processor uses this name to create a delegate representation in the loaded object tree and adds the specified handler to an internal handler list.

In XAML, the API being used (managed or JavaScript) affects the technique of specifying event handlers. The API is mutually exclusive on a XAML page level. The signal for which API is used is the presence or absence of the x:Class attribute on the root element of a XAML page. If x:Class exists, the page uses the managed API. If x:Class is absent, the page uses the JavaScript API.

In the managed API, the event handler must exist in the code-behind file that is associated with the current XAML page, because the partial classes from XAML and code must be joined in order to add the handler. For details, see Code-Behind and Partial Classes or Events Overview for Silverlight.

The following XAML example shows how to add a handler for the Loaded event for the Canvas, which in this example is the root of a XAML file. The absence of x:Class on this root indicates the JavaScript API. Resolution of the function name is therefore deferred until run time. At run time, when the event occurs, the JavaScript scripting scope is checked for a member named "onLoaded" and that function is executed.

XAML
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Loaded="onLoaded" />

The function named onLoaded is defined in a JavaScript file. This JavaScript file is associated with the HTML of the hosting page through the src parameter of the <SCRIPT> tag in HTML. This is necessary because it is the browser host that is really interpreting the script; the Silverlight plug-in is only an intermediary in the processing of the JavaScript API and does not provide the actual script engine. There is nothing in the XAML that must reference a specific JavaScript file; that is only relevant at the browser and DOM level.

html
<!-- Reference the JavaScript file where the event functions are defined 
     from the plug-in host HTML page. -->
<script type="text/javascript" src="eventfunctions.js">
... 
</script>

Most Silverlight-based applications are generated by both markup and code-behind sources. Within a project, the XAML is written as a .xaml file, and a CLR language such as Visual Basic or C# is used to write a code-behind file. When a XAML file is compiled, the location of the XAML code-behind file for each XAML page is identified by specifying a namespace and class as the x:Class attribute of the root element of the XAML page.

The primary application-level mechanism for adding a behavior for an object element is to use an existing event of the class, and to write a specific handler that is invoked when that event is raised at run time. The event name and the name of the handler to use are typically specified in the markup, whereas the code that implements your handler is defined in the code-behind.

A XAML file must have only one root element, in order to be both a well-formed XML file and a valid XAML file. The following example shows the root element of a typical XAML file for a Silverlight "page" with the root element UserControl.

XAML
<UserControl x:Class="MySilverlight.Page"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
>
  <Grid Background="OldLace">
    <!--more content here-->
  </Grid>
</UserControl>

The root element also contains the attributes xmlns and xmlns:x. These attributes indicate to a XAML processor which XML namespaces contain the element definitions for elements that the markup references.

The xmlns attribute in the previous example specifically indicates the default XML namespace. Within the default XML namespace, object elements in the markup can be specified without a prefix. For Silverlight, the default XML namespace is almost always mapped to the Silverlight client namespace, http://schemas.microsoft.com/winfx/2006/xaml/presentation. The xmlns:x attribute in the previous example indicates an additional XML namespace, which maps the XAML language namespace http://schemas.microsoft.com/winfx/2006/xaml. Language components defined by the XAML namespace are prefixed by x: when they are referenced in the markup of a file that has this mapping. This usage of xmlns to define a scope for usage and mapping is consistent with the XML 1.0 specification. Note that the xmlns attributes are only strictly necessary on the root element of each page and on the application definition if it is provided in markup. xmlns definitions apply to all child elements of the root (this behavior is again consistent with the XML 1.0 specification for xmlns). xmlns attributes are also permitted on other elements underneath the root, and would apply to any child elements of the defining element. However, this usage is not typical in Silverlight, because frequent definition or redefinition of XML namespaces can result in a XAML markup style that is difficult to read.

NoteNote:

In the Silverlight version 1.0 era, the default XAML namespace used in templates for XAML was http://schemas.microsoft.com/client/2007. That namespace still has legacy support, but using http://schemas.microsoft.com/winfx/2006/xaml/presentation as the default namespace URI is strongly recommended for any current Silverlight XAML. This is for migration and tooling reasons: the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace is shared with WPF, and some tools may not account for the http://schemas.microsoft.com/client/2007 namespace.

For your own custom assemblies, or for assemblies outside Silverlight, you can specify the assembly as part of the XML namespace mapping. Typically, you choose a different prefix and a non-default namespace, but it is also possible to choose a different XML namespace as default and then map Silverlight to a prefix. For more information about how XML namespaces and the namespaces of the backing code in assemblies are related, see Silverlight XAML Namespaces, and Mapping XAML Namespaces as Prefixes.

The x: Prefix

In the previous root element example, the prefix x: was used to map the XAML namespace http://schemas.microsoft.com/winfx/2006/xaml. This x: prefix is used to map the XAML namespace in the templates for Silverlight-based projects, in examples, and in documentation throughout this documentation set. The x: prefix/XAML namespace contains several programming constructs that you will use very frequently in your XAML. The following are the most common x: prefix/XAML namespace programming constructs you will use:

  • x:Key: Sets a unique key for each resource in a ResourceDictionary.

  • x:Class: Specifies the CLR namespace and class name for the class that provides code-behind for a XAML page, and names the class that is created by markup compile. You must have such a class to support code-behind, or to support being initialized as a RootVisual, and it is for these reasons that you almost always see x: mapped, even if there are no resources.

  • x:Name: Specifies a run-time object name for the instance that exists in run-time code after an object element defined in XAML is processed. You use x:Name for naming scenarios in the occasional cases where the more convenient FrameworkElement..::.Name property is not supported.

There are additional programming constructs in the x: prefix/XAML namespace, which are not as common. For details, see XAML Namespace (x:) Language Features.

Creating a ResourceDictionary is a common task that is usually accomplished by authoring all of the resource dictionary in XAML. For more information, see Resource Dictionaries.

Structure Definitions in Silverlight XAML

You often can declare property values that are structures using a "mini-language" attribute syntax that is enabled by a structure's type converter. However, in order to define a structure as a resource, you must define the structure as an object element in a ResourceDictionary. This is necessary because your structure needs an x:Key if it exists in a ResourceDictionary. Silverlight XAML has an issue with some structures such that you cannot assign values of that structure using attribute syntax. Structures where this issue exists include CornerRadius, GridLength, Rect, Size, Thickness and Color. To assign values for these structures, you use a variation of object element syntax known as initialization text syntax. This consists of an opening element, initialization text inside that element as inner text, then a closing element. You use the same string form for initialization text as is used by the type converter "mini-language" for attribute syntax enabled by the structure. For example, the following XAML shows a ResourceDictionary definition for a Thickness, which has an x:Key and assigns values for its settable properties using initialization text:

<ResourceDictionary>
  <Thickness x:Key="offsetBottomThickness">10,10,10,40</Thickness>
  ...
</ResourceDictionary>
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker