Introduction to Windows Presentation Foundation and XAML

by Keyvan Nayyeri
Summary
In the second part of our articles series about the UniveRSS showcase application we introduce Windows Presentation Foundation and XAML. These are the main technologies that were used to build UniveRSS. This article introduces the two technologies, some key concepts behind them and provides some basic examples. We give you some references for further reading.
Overview
.NET Framework 3.0 was released in November 2006 by Microsoft. This new version of .NET has a high correlation with Windows Vista and comes with new technologies to support needs for a new age of software. Main new technologies included in .NET 3.0 are Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation.

As our primary focus in the UniveRSS showcase application is the Windows Presentation Foundation and XAML, we’ll introduce Windows Presentation Foundation and XAML as a markup language especially built to work with this technology.
Windows Presentation Foundation
Windows Presentation Foundation (abbreviated as WPF), which was codenamed Avalon, is Microsoft’s new technology for building user interfaces in .NET 3.0 and Windows Vista. Therefore it’s all about UI and nothing else. Community members predict that Windows Presentation Foundation can get a very popular software technology in 2007. Already there are some great and beautiful applications designed with it but you’ll see more in future months.

Windows Presentation Foundation has great advantages in comparison with older user interface engines. It simplifies the process to build dynamic interfaces and visual effects. On the other hand it’s easy to create 2D and 3D animations using WPF.

This technology actually consists of a rich set of APIs which are tied to a new markup language named XAML (you’ll read about it in next section). So Windows Presentation Foundation lets you to create user interfaces based on programming and markup codes and this is a major enhancement in UI design for desktop applications.

Not only you can use WPF in Windows Vista but also you can enjoy its power in Windows XP and Windows 2003 by installing .NET Framework 3.0.
XAML
XAML (abbreviated from eXtensible Application Markup Language) is an XML child that is build by Microsoft to be used with Windows Presentation Foundation. XAML can be compared with some other markup languages such as HTML, XHTML or SVG that were used to declare user interfaces. But XAML has many major differences.

And XAML has striking benefits over older technologies and has an excellent implementation in conjunction with Windows Presentation Foundation.

One of the main goals of XAML is to separate the code logic of an application from its UI so it’s similar to MVC.

XAML represents .NET classes in a hierarchy manner so each element in XAML represents a CLR class. This has two advantages:
  • Extension will be easier because you can extend .NET classes easily.
  • Learning this markup language won’t be much different than learning Windows Presentation Foundation APIs because most things are shared between them.
Like all other XML based markup languages XAML consists of elements, attributes and namespaces. All XML rules can be applied to XAML but it has some own rules.

But generally XAML comes with these advantages:
  • Building user interfaces is easier and needs less code.
  • Transferring user interfaces designed with XAML between platforms is easy because they’re simple XML text files.
  • It’s possible to divide the process of designing a user interface between two groups and let markup designers work on layout and other stuff while some other developers work on the code logic. So it’s not necessary to have a programming knowledge to declare and design an interface because most things will be built with markup. This is very similar to the process of designing a web site. XHTML and CSS designers work on UI and ASP.NET developers write the code.
A large part of the learning curve for WPF and XAML consists of understanding the hierarchy of classes, their properties and their usage to apply them both in WPF and XAML.

Default namespace for XAML files is http://schemas.microsoft.com/winfx/2006/xaml/presentation and there is a secondary namespace http://schemas.microsoft.com/winfx/2006/xaml named "x" and should be used for some declaration and classes that aren’t available in default namespace.

Another nice point about controls in XAML is you don’t need to set an identifier or name for a control unless you need to refer to this control somewhere in your code.
Elements
As we stated before, each element in XAML represents a CLR class. Most of XAML elements correspond to a derived class from some abstract classes in CLR. Some base classes are common in XAML. For example the most common one is System.Windows.UIElement.

On the other hand there are five types of elements in XAML:
  • Root elements: These elements are root elements in your XAML files. Window and Page are most common root elements and Window is more common.
  • Panel elements: These elements are used to lay out user interfaces and keep other elements. StackPanel, DockPanel, Grid and Canvas are four panel elements.
  • Control elements: These elements are used to represent controls in XAML.
  • Geometric elements: These elements are used to draw a geometric shape in the user interface.
  • Document elements: Most common usage of these elements is when you want to change the presentation of a document. For example when you want to make a block of text bold or italic. There are two general types of document elements (Inline and Block). Two examples of inline elements are Bold and LineBreak and two examples of block elements are Paragraph and List.
Attributes
When elements represent .NET CLR classes their attributes should represent class properties and that is true. So in an inheritance hierarchy each element inherits some properties from its parent.

There are two options to define attributes:
  • Inline: Definition is similar to normal XML attributes.
  • Explicit: In this option you declare attributes as a child of the parent element. This way your code will be easier to read and understand. Explicit definition is a good choice when an element has many attributes.
Listing 1 and Listing 2 are two examples of inline and explicit definitions for attributes.
Listing 1:
<Label Background="Aquamarine">
    This is a label
</Label>
Listing 2:
<Label>
  <Label.Background>
    Aquamarine
  </Label.Background>
  This is a label
</Label>
Attached properties are a type of attributes that will be declared in other elements, not in the element itself. So an element gets its attributes from the definition of other elements. Famous examples for attached properties are Grid.Row and Grid.Column. These two attributes represent the location of an element in a Grid control (Grid is a panel element and is similar to a table in HTML). Listing 3 and its output, Figure 1, show an example of attached properties in action.
Listing 3:
<Window x:Class="UniveRSS.Intro.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/
    xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Introduction to WPF and XAML" 
    Height="300" Width="300">
    <Grid ShowGridLines="True">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="146" />
          <ColumnDefinition Width="146" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="135" />
          <RowDefinition Height="135" />
        </Grid.RowDefinitions>
        <Label Grid.Row="0"
          Grid.Column="0" Background="Red" />
        <Label Grid.Row="1"
          Grid.Column="1" Background="MediumSlateBlue" />
    </Grid>
</Window>
Figure 1:

WPF Figure 1
Compilation
In addition to Visual Studio features for easier compilation of WPF and XAML applications, it’s also possible to use MSBuild to accomplish compilation manually.

Regardless of your choice for compilation, XAML documents will be compiled to BAML files. There are two advantages for doing this:
  • BAML files are smaller than their corresponding XAML files.
  • BAML files are faster to read so load time for user interfaces will increase significantly.
Thankfully you don’t need to know much detail about BAML to develop your applications because it’s a behind the scene part of XAML.
Development Tools
Best tool to start development for Windows Presentation Foundation and XAML is Visual Studio 2005 extension for WPF and WCF. You simply install .NET Framework 3.0, optional (but recommended) WinFX SDK and this package to enable project templates and everything necessary to develop WPF applications.

On the other hand there are some other tools to edit and test XAML markup. One of them comes with WinFX SDK and is named XamlPad and the other one is Microsoft Expression Blend.

We can recommend you to use first option (Visual Studio 2005 extension) to have Intellisense and compilation features.
An Example
An example and a short description about it may help you to understand the structure and some principles. We want to walk through a simple example and write it both with XAML markup and programming codes. In this example we create a simple window and a button in its center. User clicks on the button and a MessageBox will be shown to him.

Listing 4 is the markup code for this example and Listing 5 is the C# code for the click event.
Listing 4:
<Window x:Class="UniveRSS.Intro.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/
    xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Introduction to WPF and XAML" 
    Height="300" Width="300">
  <StackPanel>
    <Button
        Background="Orchid"
        Margin="90 110"
        Width="100"
        Height="30"
        Click="OnClick">
      Click me!
    </Button>
  </StackPanel>
</Window>
Listing 5:

<Window x:Class="UniveRSS.Intro.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/
    xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Introduction to WPF and XAML"
    Height="300" Width="300">
  <StackPanel>
    <Button
        Background="Orchid"
        Margin="90 110"
        Width="100"
        Height="30"
        Click="OnClick">
      Click me!
    </Button>
  </StackPanel>
  <x:Code>
     <![CDATA[
         void OnClick(object sender, RoutedEventArgs e)
         {
            MessageBox.Show("Hello WPF!");
         }
      ]]>
  </x:Code>
</Window>
You can see the output of this simple application in Figure 2.
Figure 2:

WPF Figure 2
On the other hand you can do above things with programming codes and WPF APIs. Listing 6 shows this. As more programming codes are necessary to accomplish same thing with programming codes, it’s recommended to use XAML whenever it’s possible.
Listing 6:
void OnClick(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello WPF!");
}
Programming Model
A Windows Presentation Foundation application consists of two things: Code and Markup. The code part may be written with one of the available .NET languages such as C# or Visual Basic but the markup part is constant and is written with XAML.

You can accomplish whatever you do with XAML by writing appropriate WPF codes or vice versa. But generally XAML is used to declare the structure and constant look and feel for your application while programming codes are used to build dynamic parts.

Like ASP.NET applications you can use two models to write your code: Code Inline and Code Behind. Here is an important advantage of XAML because it lets you divide the work between markup designers and developers. But unlike ASP.NET second model (Inline) isn’t recommended at all.

In code behind model you write your XAML codes in a separate file then use WPF codes to make it dynamic and write event handlers.

In the inline model you embed code logic in the XAML file directly. For example Listing 7 uses the inline model to do what you saw in Listing 4 and Listing 5.
Listing 7:
public Window1()
{
    InitializeComponent();

    Button button = new Button();
    button.Content = "Click me!";
    button.Background =  Brushes.Orchid;
    button.Width = 100;
    button.Height = 30;
    button.Margin = new  Thickness(90, 110, 90, 110);
    button.Click += new  RoutedEventHandler(OnClick);

    StackPanel stackPanel = new StackPanel();
    stackPanel.Children.Add(button);

    this.Title = "Introduction to WPF and XAML";
    this.Width = 300;
    this.Height = 300;
    this.Content = stackPanel;
}

void OnClick(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello WPF!");
}
In each WPF application there is an App.xaml (and its corresponding code file, App.xaml.cs or App.xaml.vb) which works as a global file for application wide declarations. You can use this file to declare a constant look and feel across your application. For example you can declare a default red background for all buttons in an application.
References
In this article, we just introduced WPF and XAML and there are tons of things to learn for beginners. As the main focus of the UniveRSS application is on Windows Presentation Foundation and animations we won’t cover much detail about other stuff in our case study and articles. If you want to learn more on WPF we recommend further on- and offline references. Thankfully there are many online resources such as tutorials, articles and blog posts written by community members which are available for free. Here we list some books, online communities and tutorials for further reading. If you’re not familiar with WPF and XAML, it is recommended to read more before getting started with our showcase articles.

Keyvan Nayyeri has been a geek and programmer since he was 10. He has a BS degree in Applied Mathematics and as an experienced software architect and developer he is also a MVP from Telligent for Community Server technology. Keyvan is a co-author for Wrox press and also an author for ASP Alliance, DotNetSlackers and Code Project .NET communities. Currently he’s contributed in some projects such as BlogML, CSModules and Windows Live Writer Plugins. He edits his blog on .NET, Community Server and Technology.
The showcases on the Panel website provide examples of the possibilities within the new technologies and source codes serving as a blueprint for beginners learning to leverage these technologies. The development of the UniveRSS feed reader and other showcases on the Panel website are accompanied by articles with detailed information on the projects' underlying technologies.

The following topics are featured in this series of articles:
  • An introduction to UniveRSS, Windows Presentation Foundation, XAML and Internet Explorer 7 platform.
  • General architecture of UniveRSS and step by step guide of its development details.
  • An overview of the Windows RSS Platform
  • The use of animations in WPF
  • An overview of the UniveRSS Architecture
You can subscribe to your local MSDN Flash newsletter using the Panel registration to get notifications about new parts of our articles.
© 2007 Microsoft Corporation. Tutti i diritti sono riservati. Note legali | Marchi | Informativa sulla privacy