Welcome!

.NET Authors: Liz McMillan, Peter Silva, Yakov Werde, Matthew Pollicove , Kevin Benedict

Related Topics: .NET

.NET: Article

XAML - The Next Step in Building Windows User Interfaces

New language represents a convergence of the Web and the Windows programming models

XAML, pronounced "zammel," stands for Extensible Application Markup Language, which made its first appearance during PDC 2003, when Microsoft unveiled its next version of Windows, known as Longhorn. XAML is a part of the new Windows API, codenamed Avalon, which in turn is part of Longhorn. Avalon presents a major jump in the user interface capabilities of Windows and promises ease of use for the developer and a much richer user interaction for the end user. Avalon is said to have support for advanced 2D and 3D vector graphics. In this article, I will take a look at what XAML is, and create a few working user interfaces using XAML and the Longhorn SDK.

What Is XAML?

XAML is an XML-based declarative programming language. The underlying concept is similar to HTML (HyperText Markup Language), which, with the advent of the Internet, has become very common. Just like HTML, XAML can be used to mark up and define the layout of text and other controls on a user interface, but the similarity ends there. Although HTML is the lingua franca of the Web, XAML is a richer language, offering the ability to create user interfaces in Windows. In addition, XAML can be compiled, and it takes full advantage of the Longhorn graphics subsystem, helping developers to produce visual effects that once required Flash. XAML is very easy to use and ties up tightly with the underlying .NET Framework and classes. The following code snippet shows a very rudimentary XAML file that when saved as a .xaml file will render a button on a Windows Form, as shown in Figure 1.


<Window     xmlns="http://schemas.microsoft.com/2003/xaml"
    Width="100"
Height="100">
<Button>Hello XAML</Button>
</Window>

As you can see, using XAML is pretty simple and straightforward, allowing us to create a user interface with very little code. Each and every XAML element corresponds to a .NET Framework class and comes with a collection of methods, properties, and events. Adding a new tag to the XAML file will instantiate the corresponding object at runtime.

All XAML elements derive from System.Windows.UIElement or System.Windows.ContentElement and therefore possess a number of common features. The XAML elements can be categorized into controls that derive from System. Windows.Control (these handle user interaction), panels that derive from System.Windows.Panel (these handle page layout), text formatting elements that derive from System.Windows.TextElement, and shapes (these handle graphic shapes).

What Microsoft brings to Windows with Avalon and XAML is similar to what it brought to the Web with the introduction of ASP.NET. Those of you familiar with the ASP.NET model know that the presentation layer is encapsulated in the ASPX file and the code-behind page encapsulates the logic and event handling code. Just like an ASPX page, procedural code and event handling can be embedded inline in the body of the XAML page along with the markup elements, or it can be placed in a separate code-behind page.

The introduction of XAML thereby goes a long way toward reducing the dichotomy between the Web and Windows programming models. Just to point out, a XAML file that doesn't contain embedded procedural code can be rendered in the browser that ships with Longhorn. However, if the XAML file contains procedural code it will need to be compiled, and attempts to render it in the browser will return an error. Listing 1 was rendered using the Longhorn browser since it does not contain any procedural code. At the time of writing, XAML-based applications currently support three .NET languages: C#, VB.NET, and JScript .NET. However, by the time Longhorn is ready for release, we can surely expect support for many more languages.

XAML Advantages

In most applications, creating the user interface involves the lion's share of the coding. By using XAML for the user interface layer and a .NET language like C# or VB.NET for the logic and event handling, developers will be able to build an application that can be easily modified without mixing presentation and logic, as is now possible over the Web with ASP.NET. This approach gives developers greater flexibility and allows them to change the user interface without rewriting the logic. Another advantage of using XAML for the user interface is that the hierarchies of the various controls on a user interface are pretty evident, unlike in the conventional programming language model. This makes the UI code much more understandable when compared to the earlier models.

Basic XAML Rules

Before I go into the details of how to create user interfaces using XAML, let's go through some of the rules that must be followed when creating an XAML page. Most of these will be familiar to those of you who are used to XML.
  • XAML files have the .xaml file extension.
  • XAML is XML based, so it must be well formed.
  • The first tag in the XAML page is the root element. All other elements are children of this root element. Also, the XML declaration (<?xml version="1.0" encoding="UTF-8" ?>) is not required.
  • Tags cannot overlap.
  • Whenever attributes are assigned values, they must be enclosed in single or double quotation marks.
  • XAML is case sensitive.
  • The inner text of an element must not include special characters such as "<" or "&". If they must be used, then they should be enclosed in a CDATA block as shown in the following snippet:

    <![CDATA[Literal text...]]>

  • You must specify the namespace that tells the XAML parser which assemblies must be searched to find the tags that are being referenced. For this, XAML uses the namespaces tag. The default namespace is

    xmlns="http://schemas.microsoft.com/2003/xaml"

Creating a User Interface with XAML

As mentioned earlier, XAML has four main categories of elements, namely those that provide the layout: controls, document-related elements, graphics, and animation elements. Let's look at some of them briefly and also see how to create some basic user interfaces.

Layout Options
In XAML, layout is handled by panels that also act as containers for other elements. In most cases we will be using them either explicitly or implicitly. XAML offers us five different options.

Canvas
This allows us to position content by absolute X and Y coordinates. It is the most flexible of the panels. Height and width properties are used to define the area of the canvas, and the elements inside the canvas are assigned coordinates relative to the upper lefthand corner of the canvas, as shown in the following code snippet. If it so happens that two or more elements overlap in a canvas, the last one overwrites the underlying area. Figure 2 shows an example of a canvas layout.


<Canvas
xmlns="http://schemas.microsoft.com/2003/xaml">
<Text Canvas.Top="20" Canvas.Left="75">Hello I am some Text placed at
 (20,75)</Text>
<Button Canvas.Top="100" Canvas.Left="0" Background="Blue">I am a Button placed
 at (100,0)</Button>
</Canvas>

DockPanel
DockPanels are used to position the content along the edges of a container. Elements can be docked either to the top, bottom left, right, or center of the container. Elements are positioned relative to each other as shown in Listing 1. Figure 3 shows an example of a DockPanel.

FlowPanel
The FlowPanel arranges the child elements in a flow one after the other (see Listing 2). If the width of the content exceeds the width of the panel, then the panel is intelligent enough to wrap the element to the next line or to clip it. Figure 4 shows an example of a FlowPanel.

GridPanel
The GridPanel arranges its child elements in a grid, i.e., into rows and columns, and also helps in building tables. In a GridPanel you can specify the number of columns and the panel automatically arranges its children into rows and columns starting from the upper lefthand cell (see Listing 3). Figure 5 shows a simple GridPanel with three columns. The button elements that are added to the panel are automatically arranged in a tabular form.

TextPanel
The TextPanel is ideal when complex text layout support is required. It has sophisticated text-formatting abilities, and can even arrange text into multiple columns. Figure 6 shows a simple example of how text is formatted inside the TextPanel. Listing 4 shows how to italicize and bold portions of the text.

Controls
XAML provides all the commonly used controls, such as radio buttons, checkboxes, and text boxes, that are found in Windows today. However, a big advantage that XAML offers is the ability to combine controls with some elements to provide much better functionality. For example, the following code snippet shows how to combine an image element and a button control to obtain an image button, as shown in Figure 7.


<Window     xmlns="http://schemas.microsoft.com/2003/xaml"
    Width="100" Height="100">
<Button Width="5in" Height="1in" Background="Pink">
<Image Source ="Pic.jpg" Width="1in" Height="1in"/>
I am a button with text and a picture
</Button>
</Window>

Resources and Styles
Resources and styles are extremely useful when a particular value or setting has to be applied to more than one element in a XAML file. A simple scenario would be if we want to set the background colors of all the buttons in a XAML file to a specific color. Each element in a XAML file has a resource collection, and we could specify a resource at that level. However, in most cases we would set the resource at a higher level - perhaps the window or panel level - and use it in its child elements. Figure 8 shows a scenario in which we have specified a resource named Mycolor in the Resource collection of the panel and used it again in its child, i.e., the button, to set its background color. We also specify another resource and use it to set the color of the text (see Listing 5).

Style is basically a kind of resource that is also a property. For example, most of the elements have a property called Style. We can define a style as a resource, give it a name, and assign the value of the property to the style we defined. Take Listing 6 as an example: we define a style called Mystyle that sets the color of the text foreground to blue. We then set the value of the style property of the second text box to Mystyle, thereby rendering it in blue. However the first text box is rendered in red, as the default style for the DockPanel sets the text foreground color as red (see Figure 9).

Another thing to note about styles is that they can be inherited. Styles also allow us to define additional property values that can be applied conditionally to the target object based on changes in that element's property values. To do this, Styles uses a property called VisualTriggers that in turn defines a collection of PropertyTriggers that actually define the property and the action to be taken. Listing 7 shows us how to change the fill color of a rectangle when we move the mouse over it by using styles.

Graphics and Animation
XAML provides very strong support for a variety of graphics and animation. For drawing there are a number of shape elements that are readily available, e.g., ellipse, rectangle, line, and polygon. Listing 8 shows how to render a rectangle and an ellipse using XAML and figure 10 shows the actual rendering.

To animate a property in XAML, we have to associate the animation collection with that property. This can be done directly or by using the animation property of that property. There are a variety of animation collections that are associated with a particular property, e.g., if we are animating the color, we would use Coloranimation, and if we are animating the length we would use LengthAnimation. In most cases a property should be assigned a base value before it is animated. Listing 9 shows a scenario in which we are animating the width of the button. Since width has to have a length associated with it, we would use LengthAnimation. In this particular example, XAML animates the length of the button from the preset width of 20 to 200 and does that for 500 times.

XAML utilizes transforms to do some complicated things like stretching, shrinking, or rotating the controls pretty easily using very little code. Some of the commonly used transforms are the RotateTransform, which enables us to rotate an element by a particular angle. SkewTransform is another kind of transform that, as the name suggests, allows us to skew things. ScaleTransform scales an object in the two-dimensional x/y plane, starting from a defined center point. In Listing 10 we modify Listing 8 by adding a rotatetransform, a scaletransform, and a skewtransform. Since these shape elements do not have a transform property, we make use of a TransformDecorator element to transform the child element (see Figure 11).

Wiring Up Events

XAML helps us to create user interface elements. However, most of the user interface elements can have events associated with them. Let's take Listing 11, which shows a XAML file that renders a text box and a button (see Figure 12) and see how to wire up some event handling code to an event.

Let's say we want the text in the text box to be displayed in a message box when we click on the button. For this we need an event handler for the click event of the button. XAML can create and display the button and hook the event to an event handler, but it cannot be used to write the event handler. The event handling code will have to be written in either C#, VB.NET, or JScript .NET. XAML offers us two distinct ways of doing it.

The first way is by embedding event handling code in the XAML file, as shown in Listing 12. When the event handling code is embedded inside the XAML file, the event handling code is placed in the <def:code> tag. All programming code has to be contained within the <def:code> tag. The code is then again placed in a CDATA block so that the markup parser will not try to parse the code. The event handling code is wired to the event by setting the value of the Click attribute to the name of the event handling method, which in this case is Buttonclick.

Listings 13 and 14 show a second way to wire up the event with the event handling code. Here we move the event handling code into the code-behind page. We have also made some changes to the XAML file. In Listing 13, we add a line:

def:Class="TestSpace.MyFirstApp"

which assigns a name for the class that would be created when we compile the XAML file. TestSpace is the namespace that we will use. Another addition to the XAML file is the line

def:CodeBehind="Listing14.xaml.cs"

Here we tell the compiler the name of the code-behind file associated with the XAML file. Listing 14 shows the code-behind file. We use exactly the same class name used in the XAML file. However, we add the keyword partial, which allows us to define a C# class in more than one physical file and at the time of compilation, the definitions in the multiple files are combined into a single class. In our example, one-half of the file is in the XAML file and the other half is in the code-behind C# file.

Creating the Executable Adding an Entry Point

We have looked at how to create the user interface and we've also seen how to wire up events. Now let's see how to compile this XAML file into a Windows application. Before we do that, we have to define the main method in a XAML file, as shown in Listing 15. Similar to what we have done before, we add a line to the XAML file (def:Class="My FirstApp" ) and specify the class name that we refer to in the main method. Listing 16 shows the code-behind C# file with the main method.

Specifying the Project File
Once we have added an entry point to the application, the next step in building the executable is to create an XML-based project file that is the input to the new build system. All project files begin with a root element definition named Project, which has an attribute, DefaultTargets, that specifies the names of the targets that the system should build.

The project file has three distinct sections, namely the import section, the property group section, and the item group sections. The import section specifies the build file that contains all the rules for building a Windows application. In the property group section we specify the language that we will use and the Target Name that is the name of the application. Listing 17 shows a sample project file. Here, we set C# as the language and testapp as the name of the executable that is to be created. The item group section tells the build system which files to include. In this case we tell the build system to build all C# and XAML files.

Building the Executable

The final step is to compile the files and create the executable. To do this, we will be using the build system that ships along with the Longhorn SDK. The build system has a program called MSBuild, which compiles the XAML files, the code-behind files, and any other resource files into an executable. If the MSBuild is run without any command-line arguments, it searches the current directory for a project file. When it finds one, it builds the project according to the rules specified in that file. Now, to build our project file that has been saved as FirstXAMLProject.proj, we use the command-line option, as shown below.

c:\msbuild FirstXAMLProject.proj

The build system places the executable in the release folder. Figure 13 shows the Windows application we just created.

Conclusion

In this article we looked at what XAML is and how it can be used to build user interfaces. XAML represents a big change from the traditional way of building user interfaces for Windows. It also represents a convergence of the Web and the Windows programming models. XAML will no doubt make it easier for the developer to design and code applications.

Resources

  • The Longhorn SDK: http://longhorn.msdn.microsoft.com
  • MSDN TV (Episode: Lap Around Longhorn): http://msdn.microsoft.com/msdntv
  • MSDN TV (Episode: XAML Beyond the Basics): http://msdn.microsoft.com/msdntv
  • More Stories By Jeevan Murkoth

    Jeevan Murkoth is a Microsoft Certified Solutions Developer (MCSD) in .NET (Early Achiever) and a Microsoft Certified Application Developer (MCAD) in .NET. He currently consults for Tennessee Valley Authority and lives in Chattanooga, TN. He has an MS in Management Information Systems from Texas Tech University.

    Comments (2) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    Jeff Damask 06/17/04 01:54:02 PM EDT

    Wow XAML is cool .Article gives a very nice intro.Compiling the sample code was a breeze

    berglund gronholm 05/18/04 01:22:03 PM EDT

    pardohn my english... I'm from finland. the author is confused. in code he uses msavalon.windows namespace while in article he uses system.windows!!? i compile the code on my longhorn built and it works..