Export (0) Print
Expand All

XAML Overview

Silverlight

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. Specifically, XAML can initialize objects and set properties of objects, using a language structure that shows hierarchical relationships between multiple objects, and using a backing type convention that supports extension of types. 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 declare in XAML. The XAML language supports interchange of sources between different tools and roles in the development process without information loss, such as exchanging XAML sources between Visual Studio and Microsoft Expression Blend.

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.

<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>

In the Silverlight architecture, and in the Silverlight application development process, XAML plays several important roles.

  • XAML is the primary format for declaring a Silverlight UI and elements in that UI. Typically at least one XAML file in your project represents a "page" metaphor in your application for the initially displayed UI. Additional XAML files might declare additional pages for navigation UI or modal replacement UI. Other XAML files can declare resources, such as templates or other elements of the application that can either be re-used or replaced.

  • XAML is the format that is used for declaring styles and templates applied to the logical basis of Silverlight controls and UI. You might do this either for templating existing controls, or if you are a control author that supplies a default template for your control. When used to define styles and templates, XAML is often declared as a XAML file with a ResourceDictionary root.

  • XAML is the common format for designer support of creating Silverlight UI and exchanging the UI design between different designer applications. Most notably, XAML for a Silverlight application can be interchanged between Expression Blend products and Visual Studio.

  • WPF also defines its UI in XAML. In relationship to WPF XAML, Silverlight XAML uses a shared default XAML namespace, and has an approximate WPF-subset relationship for its XAML vocabulary. Thus, XAML promotes an efficient migration pathway for UI between Silverlight and WPF, in such a way that you could perform UI design for Silverlight and then migrate that same design to WPF with little or no redesign of the UI surface.

  • Silverlight XAML defines the visual appearance of a UI, and an associated code-behind file defines the logic. The UI design can be adjusted without necessarily making changes to the logic in code-behind. XAML in this role simplifies the workflow between individuals who might have a primary visual design responsibility and individuals who are responsible for application logic and information design.

  • Because of the visual designer and design surface support, XAML supports rapid UI prototyping in the early development phases, and makes it more likely that elements of the design can be preserved as code access points throughout a development process even if the visual design changes radically.

Depending on your own role in the development process, you might not interact with the XAML language or XAML syntax extensively. The degree to which you do interact with Silverlight XAML also depends on which development environment you are using, whether you use interactive design environment features such as toolboxes and property editors, and the scope and purpose of your Silverlight application. Nevertheless, it is likely that during development of a Silverlight application, you will be editing a Silverlight XAML file at the element level using a text-based editor. This topic is intended to educate you about the specifics of the XAML language and XAML syntax. Also, this topic calls out some aspects of usage and behavior for XAML that may be specific to Silverlight, as opposed to other XAML-utilizing frameworks such as WPF or WCF. Using this information, you should be able to confidently edit XAML for Silverlight in a text representation and maintain the validity of that XAML file's declarations and purpose when it is consumed by tools, markup compile operations, or the Silverlight run-time load of your application.

By a broad definition for programming, a namespace determines how string tokens that reference programming entities are interpreted. A namespace can also resolve ambiguities if string tokens are re-used. The existence of a namespace concept enables a programming framework to separate user-declared tokens from framework-declared tokens, to disambiguate possible token clashes through namespace qualifications, and so on. A XAML namespace is a namespace concept that serves this purpose for the XAML language. Both in its general purpose and for its application to Silverlight, XAML is used to declare objects, properties of those objects, and object-property relationships expressed as hierarchies. The objects you declare are backed by type libraries. The libraries in question might be any of the following:

  • Silverlight core libraries that are available in any distributed runtime.

  • Distributed libraries that are part of the Silverlight SDK, which you redistribute in your package (possibly with the application library caching option).

  • Libraries that represent the definition of a third-party control that your application incorporates and your application package redistributes.

  • Your own library, as created by your Silverlight project, that holds some or all of your application's Silverlight user code.

  • Another library that you define in a separate project, and reference through the Silverlight application model by using one of several Web deployment strategies.

The XAML namespace concept uses XML-style namespace declarations (xmlns) from markup, and associates backing type information with particular XAML namespaces. The identifier for the XAML namespace can be a URI, or a string token in the form of CLR-namespace and assembly information. This enables a XAML processor that reads a XAML file to differentiate tokens in the markup, and to look up types and members from the backing assemblies associated with that XAML namespace when creating a run-time object representation.

A XAML file almost always declares a default XAML namespace in its root element. The default XAML namespace defines which elements can be declared without further qualifying them by a prefix. For example, if you declare an element <Balloon />, that element Balloon is expected to exist and be valid in the default XAML namespace. In contrast, if Balloon is not in the defined default XAML namespace, you must instead qualify that reference with a prefix, for example <party:Balloon />. The prefix indicates that the entity exists in a different XAML namespace than the default namespace, and in particular that you have mapped a XAML namespace to the prefix party for usage purposes.

XAML namespaces apply to the specific element on which they are declared, and also to any element that is contained by that element in XAML structure. For this reason, XAML namespaces are almost always declared on root elements to take advantage of this inheritance concept. For more information on XAML namespaces and inheritance concepts, see Silverlight XAML Namespaces, and Mapping XAML Namespaces as Prefixes.

In Silverlight, the default XAML namespace includes nearly all of the Silverlight-defined types from the core library System.Windows.dll that are useful to declare in XAML. The default XAML namespace enables omitting CLR namespace qualification, and is analogous to the convenience of a using or Imports statement in a code file. The difference is that a default XAML namespace can encompass types that can come from multiple CLR namespaces. For example, using the default Silverlight XAML namespace, <Button /> refers to System.Windows.Controls.Button, and <ImageBrush /> refers to System.Windows.Media.ImageBrush. This is enabled because the System.Windows.Controls and System.Windows.Media CLR namespaces are both mapped to the default XAML namespace for Silverlight, as declared by how the core libraries are constructed.

Silverlight libraries that are distributed as part of the Silverlight SDK generally require a prefix mapping in order to use their types in XAML.

The SDK libraries are CLR-attributed such that designers that load the assemblies can suggest a particular prefix. In Visual Studio, for any assemblies that are already referenced by a project, you can use an auto-complete feature that reads the CLR attributing in referenced assemblies. This Visual Studio feature either presents all possible XAML namespaces as a dropdown, or uses the suggested prefix as a hint to help suggest a particular mapping choice.

Silverlight SDK assemblies define a URI-based XAML namespace, which enables multiple libraries and multiple CLR namespaces within the libraries to share the XAML namespace. For more information, see Prefixes and Mappings for Silverlight Libraries.

Types that come from libraries other than the Silverlight core libraries will require that you declare and map a XAML namespace with a prefix in order to reference the types from that library. Typically, if a library does not support a URI-based XAML namespace, the XAML namespace declaration needed in order to access the library's types in XAML requires three pieces of information:

  • A prefix, which defines the markup token that is used to reference that XAML namespace in subsequent XAML markup.

  • The assembly that defines the backing types of elements in that XAML namespace, which a XAML processor must access in order to create objects based on the XAML declarations.

  • A CLR namespace within that assembly.

For more information on XAML namespaces, including mapping custom types from user code, or types from third-party libraries, see Silverlight XAML Namespaces, and Mapping XAML Namespaces as Prefixes.

The XAML Language XAML Namespace

One particular XAML namespace that is declared in nearly every Silverlight XAML file is the XAML namespace for elements that are defined by the XAML language. By convention, the XAML language XAML namespace is mapped to the prefix x:. The default project and file templates for Silverlight projects always define both the default XAML namespace (no prefix, just xmlns=) and the XAML language namespace (to prefix x:) as part of the root element. For example, the following example snippet is a template-created UserControl root of the initial page for a Silverlight application (showing the opening tag only, and simplified):

<UserControl  
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
...>

The x: prefix/XAML language XAML namespace contains several programming constructs that you will use frequently in your Silverlight XAML. The following are the most common x: prefix/XAML namespace constructs:

  • x:Key: Sets a unique user-defined key for each resource in a ResourceDictionary. The key token string is used as the argument for StaticResource Markup Extension to retrieve any such resource from another XAML usage.

  • 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 or joined by the XAML markup compiler build action in the Silverlight application model. You must have such a class to support code-behind, or to support being initialized as a RootVisual. It is for these reasons that you almost always see x: mapped, even if there are no resources and you never use x:Name.

  • 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 element-naming scenarios in the occasional cases where the more convenient FrameworkElement.Name property is not supported.

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

Other XAML Namespaces

You may encounter XAML files for Silverlight that define the prefixes d: (for designer namespace) and mc: (for markup compatibility). Generally these are for infrastructure support that is related to exchanging the XAML between tools or processes, and you do not need to interact with elements in these namespaces in typical Silverlight XAML. For more information, see "Other XAML Namespaces" section of Silverlight XAML Namespaces, and Mapping XAML Namespaces as Prefixes. For more information on the sdk: prefix, see Prefixes and Mappings for Silverlight Libraries.

For legacy reasons, Silverlight XAML also supports another URI-based namespace http://schemas.microsoft.com/client/2007 as the possible default XAML namespace. Generally, you should use http://schemas.microsoft.com/winfx/2006/xaml/presentation as the default XAML namespace for Silverlight application programming, and should not use http://schemas.microsoft.com/client/2007 for current applications.

A XAML file always has exactly one element serving as its root, which declares an object that will be the conceptual root of some programming structure such as a page, or the object graph of the entire run-time definition of an application.

In terms of XAML syntax, there are three ways to declare objects in XAML:

  • Directly, using object element syntax: uses opening and closing tags to instantiate an object as an XML-form element. You can use this syntax to declare root objects or to create nested objects that set property values.

  • Indirectly, using attribute syntax: uses an inline string value to declare an object. In concept, this could be used to instantiate any object other than the root. 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 some procedure that knows how to create a new object on basis of knowing which property is being set, type system characteristics of that property, and the supplied string value. Typically, this means that the type or property in question either supports a type converter that can process the string input, or the XAML parser enables a native conversion.

  • Using a markup extension: markup extensions are a concept that will be explained in a subsequent section of this topic.

This does not mean that you always have the choice of any syntax for object creation in a given XAML vocabulary. Certain objects from the vocabulary 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. In fact, objects that can be created with either object element or attribute syntax are comparatively rare in Silverlight. Even when both syntax forms are possible, one of the syntax forms tends to be the dominant or most scenario-appropriate form to use.

In addition to declaring an object in a way that equates to instantiating that object, there are also techniques you can use in XAML to reference existing objects. Those objects might be defined either in other areas of XAML, or exist implicitly through some behavior of the platform and its application or programming models. Using object references 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 tags using the following pattern, where objectName is the name of the type that you want to instantiate. In this documentation, you will often see the term object element usage, which is shorthand for the particular markup that is used to create the object in object element syntax.

< objectName >

</ objectName >

The following example is object element usage to declare a Canvas object.

<Canvas>
</Canvas>

Many Silverlight objects, such as Canvas, can contain other objects.

<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-closing tag instead of an opening/closing pair, as shown by the <Rectangle /> tag in the following example.

<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 that sets the property, and to initialize 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 syntactical step.

Initialization Text

You sometimes can declare objects along with a contained inner text that supplies initial values for construction. In XAML, this technique and syntax is called initialization text. Conceptually, initialization text is similar to calling a constructor that has parameters, but the internal XAML parser implementations typically do not do that literally.

Initialization text is useful in Silverlight for setting initial values of some structures. You use this technique if you want the structure instance created within a resource dictionary, because you intend to share that structure value to multiple target properties. In certain structures, you cannot use attribute syntax to set the structure's values. Structures where this issue exists are: GridLength; Color.

Note Note:

If targeting Silverlight 4; this issue affects additional structures; for more information, see XAML Processing Differences Between Silverlight Versions.

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 the implicit collection syntax).

As with object declaration, this list of techniques for setting properties of objects in XAML 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 a more verbose form through property element syntax, or an alternative 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 properties on objects in Silverlight that cannot be set in XAML by any means, and can only 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 helper method that is not strictly the property accessor, or a calculated property. A calculated property relies on the values of other settable properties plus perhaps a service or behavior influence on that property value; these features are available in the dependency property system. For more information on dependency properties, see Dependency Properties Overview.

Collection syntax in XAML gives 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 syntax enables 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 four attributes to set the Name, Width, Height, and Fill properties of a Rectangle object.

<Rectangle Name="rectangle1" Width="100" Height="100" Fill="Blue" />

If you had a direct view of how the XAML parser interprets this markup and defines the object tree, the equivalent code might resemble the following pseudocode:

Rectangle rectangle1 = new Rectangle();

rectangle1.Width=100.0;

rectangle1.Height=100.0;

rectangle1.Fill = new SolidColorBrush(Colors.Blue);

The first line is a call to the default constructor. Note that the value of Name is used as the instance name to assign the constructor result to. For more information on the importance of Name and how it relates to the Silverlight XAML parser behavior and the Silverlight programming model, see XAML Namescopes.

Other than Name, the order of assignment for the second through fourth lines of the pseudocode above is indeterminate. By the rules of XAML, a XAML parser must be able to set these properties in any order once the instance is created.

Setting a Property by Using Property Element Syntax

Many Silverlight 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.

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

Setting a Property by Using XAML Content Syntax

Some Silverlight types define a property that enables a XAML content element syntax. In XAML content element syntax, you can omit the property element for that property, and can set the property by providing content within the owning type's object element tags. That content is typically one or more object elements. This is known as XAML content syntax. If XAML content syntax is available, the syntax will be shown in the XAML Usage sections for that property in the Silverlight reference documentation.

For example, the Child property page for Border shows XAML content syntax instead of property element syntax to set the single-object Child value of a Border. The following example parallels that usage:

<Border>
  <Button .../>
</Border>

If the property that is declared as the XAML content property also supports a "loose" object model where the property type is Object, or specifically is type String, then the XAML content syntax can be used to place a pure string as the content between the opening and closing object tags. For example, the Text property page for TextBlock shows an alternative XAML syntax that uses XAML content syntax instead of attribute syntax to set a string value for Text. The following example parallels that usage and sets the Text property of a TextBlock without explicitly specifying the Text property. Text is set using what XML would consider to be content or "inner text," rather than using an attribute, or declaring an object element.

<TextBlock>Hello!</TextBlock>
NoteNote:

If you are specifically targeting Silverlight 3, see XAML Processing Differences Between Silverlight Versions and WPF. Silverlight 3 uses different XAML parsing behavior than Silverlight 4. Silverlight 3 XAML supports only a limited number of XAML content syntaxes. 

Setting a Property by Using a Collection Syntax

In XAML, there are several variations of collection syntax. 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 an existing collection. The XAML language and XAML processors implementing XAML support rely on a convention in backing collection types to enable this syntax.

Generally, the property of the collection type that holds the collection items (such as an indexer or Items property) is not present in the XAML syntax. For collections, what is really necessary to do anything useful with a collection from XAML is not necessarily a property, but a method: the Add method. Calling the Add method is the aforementioned convention. When the XAML processor encounters one or more object elements within a XAML collection syntax, each such object is first created by using its object tagging, then each new object is added to the containing collection in declaration order 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).

<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, for a Silverlight property that takes a collection, a XAML parser implicitly knows the collection's backing type, 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.

<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 XAML content property for the class. This is the case with the GradientStops property being used in the previous examples, and in many other Silverlight properties. In these syntaxes, you can also omit the property element. This results in the following markup:

<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, views, or items controls. For instance, the following examples show the explicit XAML and the simplest possible XAML for compositing two UI elements within a StackPanel.

<!--explicit tags, and UIElementCollection commented-->
<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 an object tree, you cannot specify it explicitly in XAML. This is because UIElementCollection is not a constructible class. The value you get in a runtime object tree is a default initialization value from the owning class, which cannot be changed after initialization. Scenarios exist 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 backing type's characteristics, or because they are filling a read-only collection property.

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.

<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).

<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.)

<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 markup extension usage such as 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.

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

Markup extensions are a XAML language concept that is used prominently in the Silverlight XAML implementation. In XAML attribute syntax, curly braces { and } indicate a markup extension usage. 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 the following markup extensions that are defined under the default Silverlight XAML namespace and understood by its XAML parser:

  • Binding: supports data binding, which defers a property value until it is interpreted under a data context.

  • StaticResource: supports referencing resource values that are defined in a ResourceDictionary.

  • TemplateBinding: supports control templates in XAML that can interact with the code properties of the templated object.

  • RelativeSource: enables a particular form of template binding.

Silverlight also supports a very basic markup extension that is defined in the XAML language 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 from some other part of the object graph for the application, or defer a value to run time. 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 example, the following XAML 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 defined as a keyed resource in a resource dictionary.

<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. For more information on the resource dictionary concept introduced here, see Resource Dictionaries.

In many cases, a markup extension can be used to provide a value that is a reference to an existing object, or can provide an object that enables the property to be set in attribute form. For more information, see the "Markup Extensions" section of the topic XAML Usage Syntax.

Silverlight 5 introduces a base class that enables defining custom markup extensions. For more information, see IMarkupExtension<T>.

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.

A type converter is the conceptual entity that takes an attribute value from XAML, and uses the string value to create a result value that is not literally a string. Type converters are associated with the backing types of objects or sometimes their specific properties. Accessing the type converter does not require any special usage from XAML markup. A XAML processor reads the backing types as part of the general type-mapping behavior that a XAML processor performs, determines whether those types support a type converter, and invokes that type converter when necessary to obtain values.

As stated previously in the "Setting Properties" section, type converters enable attribute syntax in cases where property syntax might otherwise be required. Generally this is done in order to simplify the markup forms. Some type converters have relatively simple behavior for conversion. For example, NullableBoolConverter supports the ability to specify the three possible states of a Nullable<bool> value as the strings true, false, and {x:Null}. In the Silverlight reference documentation, the XAML syntax that type converters enable is not typically found on the backing TypeConverter classes. Instead, you will find details on the attribute syntax on the reference pages for each the objects or properties where you can use that typeconverter-enabled syntax. Typically, there is no need to invoke TypeConverter methods directly in Silverlight.

A small number of type converters support a fairly complex "mini language" that may require a syntax or grammar guide to fully understand. An example is Property Path Syntax, which documents the grammar that is relevant for properties such as Path that use PropertyPathConverter.

Type converters mostly exist in Silverlight as support classes for XAML, and to serve as base classes for anyone authoring a type converter to support a custom type.

For more information about type converters for XAML, including how to define your own type converter to support a custom type for XAML, see TypeConverters and XAML.

Note Note:

Event handling from XAML differs if you are using the JavaScript API for Silverlight. Those differences are not documented here; see XAML and XAML-Related Concepts in the JavaScript API for Silverlight.

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. The XAML event syntax convention can then be extended by specific technologies such as Silverlight, which integrate the XAML-declared events through the programming model. You specify the name of the relevant 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.

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 markup-compiled as part of a build action for Silverlight projects, 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.

For more information on how these mechanisms work in XAML and how they relate to the Silverlight programming and application models, see Code-Behind and Partial Classes or Events Overview for Silverlight.

Creating a ResourceDictionary is a common task that is usually accomplished by authoring all of the resource dictionary in XAML. However, resource dictionaries and how to use them is a larger conceptual area that is outside the scope of this topic. For more information, see Resource Dictionaries.

The XAML language is fundamentally based on the XML language. Any valid XAML file is by definition a valid XML file. However, XAML extends XML significantly. In particular it treats the concept of schema quite differently because of its relationship to the backing type concept, and adds language elements such as attached members and markup extensions. xml:lang is valid in XAML, but influences runtime rather than parse behavior, and is typically aliased to a framework-level property; for more information, see FrameworkElement.Language. xml:base is valid in markup but is ignored by Silverlight XAML. xml:space is valid, but is only relevant for scenarios as discussed in the Whitespace Processing section. The encoding attribute is valid in XAML. Only UTF-8 and UTF-16 encodings are supported. UTF-32 is not supported.

Case Sensitivity in XAML

XAML as a language is case-sensitive. This is another consequence of XAML being based on XML, which is case-sensitive. 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.

In Silverlight 3, Silverlight used a different XAML parser. In the Silverlight 4 and later run times, both parsers exist side-by-side, which provides backward compatibility for XAML parsing. There are some specific variations in the XAML forms that each of the XAML parsers is capable of processing.

This topic describes XAML in Silverlight as based on the Silverlight 5 XAML parser behavior and capabilities. For more information on some of the specific differences between the XAML parsers in various Silverlight versions, see XAML Processing Differences Between Silverlight Versions. For information on how to upgrade applications to account for XAML processing differences, see XAML Processing Differences Between Silverlight Versions or Ensuring That Your Silverlight Applications Work with Silverlight 5.

There are certain differences between Silverlight XAML and WPF XAML, which might affect migration scenarios, or applications that used shared designs for UI. For more information, see XAML Processing Differences Between Silverlight Versions and WPF

Consistent with XML, whitespace characters in XAML are space, linefeed, and tab. These correspond to the Unicode values 0020, 000A, and 0009 respectively.

By default the following whitespace normalization occurs when a XAML processor processes any inner text found between elements in a XAML file:

  • Linefeed characters between East Asian characters are removed. See East Asian Characters section further down in this topic for a definition of "East Asian characters".

  • All whitespace characters (space, linefeed, tab) are converted into spaces.

  • All consecutive spaces are deleted and replaced by one space.

  • A space immediately following the start tag is deleted.

  • A space immediately before the end tag is deleted.

"Default" corresponds to the state denoted by the default value of the xml:space attribute.

Whitespace in Inner Text, and String Primitives

The above normalization rules apply to inner text found within XAML elements. After normalization, a XAML processor will convert any inner text into an appropriate type as follows:

  • If the type of the property is not a collection, but is not directly an Object type, the XAML processor attempts to convert to that type using its type converter. A failed conversion here will result in a XAML parse error.

  • If the type of the property is a collection, and the inner text is contiguous (no intervening element tags), the inner text is parsed as a single String. If the collection type cannot accept String, this also results in a XAML parser error.

  • If the type of the property is Object, then the inner text is parsed as a single String. If there are intervening element tags, this results in a XAML parser error, because the Object type implies a single object (String or otherwise).

  • If the type of the property is a collection, and the inner text is not contiguous, then the first substring is converted into a String and added as a collection item, the intervening element is added as a collection item, and finally the trailing substring (if any) is added to the collection as a third String item.

Whitespace and Text Content Models

In practice, preserving whitespace is only of concern for a subset of all possible content models. That subset is composed of content models that can take a singleton String type in some form, a dedicated String collection, or a mixture of String and other types in lists, collections, or dictionaries.

Even for content models that can take strings, the default behavior within these content models is that any whitespace that remains is not treated as significant.

For more information about controls or other types that do generally process whitespace as significant, see Text and Fonts or RichTextBox Overview.

Preserving Whitespace

There are several techniques for preserving whitespace in the source XAML for eventual presentation that are not affected by XAML processor whitespace normalization.

xml:space="preserve": Specify this attribute at the level of the element where whitespace preservation is desired. Note that this will preserve all whitespace, including the spaces that might be added by code editing applications to align markup elements as a visually intuitive nesting, but whether those spaces render is again a matter of the content model for the containing element. Specifying xml:space="preserve" at the root level is not recommended, because the majority of object models do not consider whitespace as significant one way or another. It is a better practice to only set the attribute specifically at the level of elements that render whitespace within strings, or are whitespace significant collections.

Entities and non breaking spaces: XAML supports placing any Unicode entity within a text object model. You can use dedicated entities such as nonbreaking space (&#160; in UTF-8 encoding). You can also use rich text controls that support nonbreaking space characters. You should be cautious if you are using entities to simulate layout characteristics such as indention, because the run-time output of the entities will vary based on a greater number of factors than would the general layout facilities, such as proper use of panels and margins.

East Asian Characters

"East Asian characters" is defined as a set of Unicode character ranges U+20000 to U+2FFFD and U+30000 to U+3FFFD. This subset is also sometimes referred to as "CJK ideographs". For more information, see http://www.unicode.org.

Silverlight 3 Whitespace

If you are targeting Silverlight 3, XAML processing by Silverlight 3 uses different whitespace processing rules. For more information, see XAML Processing Differences Between Silverlight Versions.

Because XAML is a markup language, some of the typical strategies for debugging within Visual Studio are not available. For more information, see Debugging Silverlight XAML.

Community Additions

ADD
Show:
© 2014 Microsoft