We introduce the XAML language and XAML concepts to the Windows Store app developer audience, and describe the different ways to declare objects and set attributes in XAML as it is used for creating a Windows Store app.
What is XAML?
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 UI elements in the declarative XAML markup. You can then associate a separate code-behind file for each XAML file that can respond to events and manipulate the objects that you originally 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 Microsoft Visual Studio and Microsoft Expression Blend. By using XAML as the interchange format, designer roles and developer roles can be separate and designers and developers can iterate during the prodiuction of an app.
XAML files are XML files that generally have the .xaml file name extension.
Basic XAML syntax
XAML has a basic syntax that builds on XML. By definition, valid XAML must also be valid XML. But XAML also has syntax concepts that are assigned a different and more complete meaning, while still being valid in XML per the XML 1.0 specification. For example, XAML supports property element syntax, where property values can be set through elements rather than string values in attributes or content. To XML, property element syntax would just be considered an element that has a dot character in the element name.
Visual Studio helps you to produce valid XAML syntax, both in the XAML text editor and in the XAML design surface. So, don't worry too much about the syntax with each keystroke. When you use a XAML editing tool, the IDE often helps you write valid syntax by providing autocompletion hints, showing suggestions in Microsoft IntelliSense lists and dropdowns, showing UI element libraries in the toolbox, or other techniques. If this is your first experience with XAML, it might still be useful to know the syntax rules and particularly the terminology that is sometimes used to describe the restrictions or choices when we describe XAML syntax in reference topics or other topics. We cover these concepts in a separate topic, Basic XAML syntax guide.
XAML namespaces
By a broad definition that applies to programming as a domain of knowledge, a namespace determines how strings or identifiers that reference programming entities are interpreted. A namespace can also resolve ambiguities if you reuse identifiers. By using namespaces, a programming framework can separate user-declared identifiers from framework-declared identifiers, disambiguate identifiers through namespace qualifications, and so on. XAML has its own XAML namespace concept that serves this purpose for the XAML language. Here's how XAML applies and extends XML namespace concepts:
- XAML uses the reserved default-namespace XML attribute xmlns for namespace declarations, and the value of the attribute is a Uniform Resource Identifier (URI).
- XAML uses prefix declarations to declare non-default namespaces, and interprets prefix usages in elements and attributes as techniques to reference that namespace.
- XAML has a concept of a default namespace, which applies even if no xmlns is specified. The default namespace doesn't have to be the XML language default namespace, and it can be defined differently for each XAML programming framework.
- Namespace definitions inherit in an XML document from parent element to child element.
- Attributes of an element inherit the element's namespaces, so it's fairly uncommon to see prefixes on attributes.
A XAML file almost always declares a default XAML namespace in its root element. The default XAML namespace defines which elements you can be declare without qualifying them by a prefix. For more info on the relationship between XAML namespaces and how to reference non-default namespace XAML elements by using prefixes, see XAML namespaces and namespace mapping.
Mapping custom types to XAML namespaces
One of the most powerful aspects of XAML as a language is that extensibility of a XAML vocabulary with custom types is simple, and is fundamentally built-in to how the language works. Frameworks are responsible for creating the backing objects, and aren't bound by specifications of what these objects are beyond the basic XAML syntax, XAML namespace constructs, and language rules.
If you use XAML for types that come from libraries other than the core libraries, you must declare and map a XAML namespace with a prefix so that you can reference the types from that library in your XAML. You declare prefix mappings as attributes. For the attribute name, you first specify the keyword xmlns:, then the prefix you want. The value of that attribute must contain the keyword using: as the first part of the value. The remainder of the value is a string token that references the specific code-backing namespace by name.
The prefix defines the markup token that is used to refer to that XAML namespace in the remainder of the markup in that XAML file. A colon character (:) goes between the prefix and the entity to be referenced within the XAML namespace.
For example, the attribute syntax to map a prefix myTypes to the namespace myCompany.myTypes is: xmlns:myTypes="using:myCompany.myTypes", and a representative element usage is: <myTypes:CustomButton/>
For more info on mapping XAML namespaces for custom types, see XAML namespaces and namespace mapping.
The XAML-language XAML namespace
One particular XAML namespace that is declared in nearly every Windows Runtime 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 Windows Store app projects always define both the default XAML namespace (no prefix, just xmlns=) and the XAML-language XAML namespace (prefix "x") as part of the root element. For example, this snippet is a template-created Page root of the initial page for an app (showing the opening tag only, and simplified):
<Page x:Class="Application1.BlankPage" 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 use often in your XAML. Here are the most common ones:
| Term | Description |
|---|---|
|
Sets a unique user-defined key for each resource in a ResourceDictionary. The key token string is the argument for the StaticResource markup extension to retrieve any such resource from another XAML usage. | |
|
Specifies the code namespace and code class name for the class that provides code-behind for a XAML page. This names the class that is created or joined by the build actions that support the XAML markup compiler when the app is compiled. You must have such a class to support code-behind, or to have your XAML content be initialized as Window.Content in a typical app activation model. | |
|
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 can use x:Name for element identification, which is useful when FrameworkElement.Name is not supported on that element type. You can think of setting x:Name in XAML as being like declaring a named variable in code, and as you'll learn later, that's exactly what happens when your XAML is loaded as a component of a Windows Runtime app. | |
|
Identifies elements that should use localized resources for some of their property values. For more info on how to use x:Uid, see Quickstart: Translating UI resources. |
Other programming constructs in the XAML-language XAML namespace exist but are not as common. For more info, see XAML namespace (x:) language features.
You need special syntax sometimes for a literal "{" value. For more info see Basic XAML syntax guide.
Other XAML namespaces
You often see XAML files that define the prefixes "d" (for designer namespace) and "mc" (for markup compatibility). Generally these are for infrastructure support, or to enable scenarios in a design-time tool. For more info, see the "Other XAML namespaces" section of the XAML namespaces topic.
Markup extensions
Markup extensions are a XAML language concept that is often used in the Windows Runtime XAML implementation. In XAML attribute syntax, curly braces "{" and "}" indicate a XAML 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 XAML parser calls code that backs that particular markup extension and provides an alternate object or behavior result. Markup extensions can have arguments, which are also contained within the curly braces. Typically, an evaluated markup extension provides an object return value that is inserted into the position in the object tree that corresponds to where the markup extension usage was in the XAML.
Windows Runtime XAML supports these markup extensions that are defined under the default XAML namespace and are understood by the Windows Runtime XAML parser:
- Binding: supports data binding, which defers a property value until it is interpreted under a data context that only exists at run-time. This markup extension supports a wide range of arguments. For more info, see Binding markup extension.
-
StaticResource: supports referencing resource values that are defined in a ResourceDictionary, which can be in a different XAML file but which must ultimately be findable by the parser at load time. The argument of a
{StaticResource}usage should identify the key for a keyed resource in a ResourceDictionary. - TemplateBinding: a special case of Binding that supports control templates in XAML and their eventual usage at run time.
- RelativeSource: enables a particular form of template binding.
Windows Runtime also supports an x:Null markup extension. You use this to set Nullable values to null in XAML. For example you might use this in a control template for a CheckBox, which interprets null as an indeterminate check state.
A markup extension generally return an existing instance from some other part of the object graph for the app, or defers a value to run time. Because you can use a markup extension as an attribute value, and that's the typical usage, you often see markup extensions providing values for reference-type properties that might have otherwise required a property element syntax. For example, here's the syntax for referencing a resusable Style from a ResourceDictionary: <Button Style="{StaticResource EditAppBarButtonStyle}"/>. A Style is a reference type, so without the {StaticResource} usage, you would've needed a <Button.Style> property element and a <Style> definition within it to set that property.
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 doesn't otherwise 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 next 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 you defined earlier 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 reference topics that describe the available markup extensions in Windows Runtime XAML, see Windows Runtime namespace extensions or XAML namespace (x:) language features.
You can nest markup extensions. The innermost markup extension is evaluated first.
Events
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 can then integrate the XAML-declared events through the Windows Runtime app programming model. 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. Most Windows Store apps are generated by both markup and code-behind sources. Within a project, the XAML is written as a .xaml file, and you use the language you prefer (C#, Visual Basic, C++) to write a code-behind file. When a XAML file is markup-compiled as part of a build action for the project, 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 info on how these mechanisms work in XAML and how they relate to the programming and application models, see Events and routed events overview.
Resource dictionaries
Creating a ResourceDictionary is a common task that is usually accomplished by authoring a resource dictionary as an area of a XAML page or a separate XAML file. Resource dictionaries and how to use them is a larger conceptual area that is outside the scope of this topic. For more info see ResourceDictionary and StaticResource references.
XAML and XML
The XAML language is fundamentally based on the XML language. But 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 info, see FrameworkElement.Language. xml:base is valid in markup but parsers ignore it. xml:space is valid, but is only relevant for scenarios described in the XAML and whitespace topic. 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 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 depends on how the attribute value is handled for particular properties. For example, if the attribute value declares a member name of an enumeration, 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, and utility methods for working with objects based on the name that the Name property declares, treat the name string as case-sensitive.
XAML namescopes
The XAML language defines a concept of a XAML namescope. The XAML namescope concept influences how XAML processors should treat the value of x:Name or Name applied to XAML elements, particularly the scopes in which names should be relied upon to be unique identifiers. XAML namescopes are covered in more detail in a separate topic. See XAML namescopes.
The role of XAML in the development process
XAML plays several important roles in the app development process.
- XAML is the primary format for declaring an app's UI and elements in that UI, if you are programming using C#, Visual Basic or C++. Typically at least one XAML file in your project represents a page metaphor in your app for the initially displayed UI. Additional XAML files might declare additional pages for navigation UI. Other XAML files can declare resources, such as templates or styles.
- You use the XAML format for declaring styles and templates applied to controls and UI for an app.
- You might do this either for templating existing controls, or if you define a control that supplies a default template as part of a control package. When you use it to define styles and templates, the relevant XAML is often declared as a discrete XAML file with a ResourceDictionary root.
- XAML is the common format for designer support of creating app UI and exchanging the UI design between different designer apps. Most notably, XAML for the app can be interchanged between Expression Blend and Visual Studio.
- Several other technologies also define the basic UI in XAML. In relationship to Windows Presentation Foundation (WPF) XAML and Microsoft Silverlight XAML (including Silverlight for Windows Phone), the XAML for a Windows Store app uses the same shared default XAML namespace. The XAML vocabulary for a Windows Store app overlaps significantly with the XAML-for-UI vocabulary also used by Silverlight and to a slightly lesser extent by WPF. Thus, XAML promotes an efficient migration pathway for UI originally defined for precursor technologies that also used XAML.
- XAML defines the visual appearance of a UI, and an associated code-behind file defines the logic. You can adjust the UI design without making changes to the logic in code-behind. XAML simplifies the workflow between designers and developers.
- Because of the visual designer and design surface support, XAML supports rapid UI prototyping in the early development phases.
Depending on your own role in the development process, you might not interact with XAML much. The degree to which you do interact with XAML files 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 Windows Store app. Nevertheless, it is likely that during development of the app, you will be editing a XAML file at the element level using a text or XML editor. Using this info, you can confidently edit XAML in a text or XML representation and maintain the validity of that XAML file's declarations and purpose when it is consumed by tools, markup compile operations, or the run-time phase of your Windows Store app.
Related topics
- Basic XAML syntax guide
- Dependency properties overview
- ResourceDictionary and StaticResource references
- Windows Runtime namespace extensions
- XAML namespaces and namespace mapping
- XAML namespace (x:) language features
- Quickstart: Creating a UI with XAML
- Application resources and localization sample
Build date: 11/28/2012