Click here to Skip to main content
11,933,621 members (54,602 online)
Click here to Skip to main content
Add your own
alternative version


771 bookmarked

A Guided Tour of WPF – Part 1 (XAML)

, 19 Apr 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A guided tour of the Windows Presentation Foundation, one feature at a time.

The WPF Horse Race application in action.

Table of contents

  • Part 1 (XAML): Learn about XAML and how it is used in WPF applications.
  • Part 2 (Layout): Learn about layout panels and how they are used to construct user interfaces.
  • Part 3 (Data binding): Learn how WPF data binding works and how it can be used.
  • Part 4 (Data templates and triggers): Learn how data templates and triggers work and how they can be used.
  • Part 5 (Styles): Learn about how UIs can be styled in WPF.


This article is the first in a series which reviews some important features of Microsoft's Windows Presentation Foundation (WPF). The entire series barely scratches the surface of the immense WPF platform, and it does not dive too deeply into any particular topic. The purpose of this series is to familiarize the reader with the basic WPF programming model to the point where he/she is comfortable enough with WPF to fully understand the, rather silly, WPF Horse Race application (available for download via a link at the top of this page).

The subject matter is presented in the context of a completely impractical horse racing application, as seen in the screenshot above. The application was designed with the intention of being used as the focal point of this series. I tried to find the right balance between making the demo application simple enough to be understandable to a WPF newcomer, yet complicated enough to actually do something interesting (or at least mildly amusing).


In order to run a WPF application you need the .NET Framework version 3.0, or greater. Windows Vista has the .NET Framework v3.0 installed by default, so you only need to install it if you have Windows XP SP2.

To develop WPF applications you should have Visual Studio 2005 with the "Orcas" extensions, or a later version of Visual Studio, and also the Windows SDK. Refer to the External Links section at the end of this article for links to relevant resources.

What is XAML?

XAML stands for eXtensible Application Markup Language. It is an all-purpose XML-based language used for declaring object graphs, which are instantiated at runtime. XAML is used by WPF developers to declare the layout of a user interface (UI), and the resources used in that UI.

It is not at all necessary to use XAML when programming in WPF. Anything that can be done in XAML can also be done in code. Using XAML makes many UI development scenarios much easier and faster, such as creating the layout of a UI and configuring styles, templates, and other WPF-specific entities discussed later in this series.

Performance impact

When you compile a WPF application in Visual Studio it will compile your XAML files into a compressed representation known as Binary Application Markup Language (BAML). The BAML is then saved as a resource in the resultant assembly. When that assembly is loaded and the resource is requested, the BAML is streamed out and very quickly turned into the object graph described by the original XAML.

This two-step process allows the XAML parsing to occur at compile time, thus mitigating the performance overhead of using a text-based object instantiation technology. With that said, it is possible to load XAML programmatically via the XamlReader.Load method. Dynamically loading XAML can be useful in a variety of situations, such as when a volatile portion of your UI is periodically downloaded from a server via XML Web services.

Basic syntax

Since XAML is an XML-based language, it should be quite simple and straightforward for anyone with XML experience. There are two different uses for XML elements in XAML; elements that represent objects and elements that represent properties of objects. An XML attribute always represents a property or event of an object. That's it; it is that simple. There are a few other concepts built on top of those fundamentals, but XAML never becomes complicated.

For example:

<Button Content="Click Me" Click="OnButtonClick">
      <GradientStop Color="Yellow" Offset="0" />
      <GradientStop Color="Green" Offset="1" />

That XAML results in a funky little button, which is rendered like this:

A Button, as configured by the preceding XAML

Let's dissect that XAML to see how it works. The <Button> element declares that an instance of the Button class will be created. That Button object will have its Content property set to the string "Click Me". The Button's Click event will be handled by a method called OnButtonClick in the code-behind file (we'll get into code-behind files soon).

The next element is <Button.Background>, which is said to use the "property element syntax". That XML element represents the Background property of the Button being configured. The child element of a property element is the value to which the property is set. In this case, the Background property is set to a LinearGradientBrush object.

That brush has two <GradientStop> child elements, which might seem confusing at first. What are those GradientStop objects doing there? What are they being assigned or added to? The answer lies in the fact that XAML has some "shortcuts" built in which allow you to specify a property on a class which is considered to be the "content property." You do not need to use the property element syntax to assign a value to the "content property" of a class. Since LinearGradientBrush's content property is the GradientStops property, the following XAML is equivalent to that seen above:

<Button Content="Click Me" Click="OnButtonClick">
        <GradientStop Color="Yellow" Offset="0" />
        <GradientStop Color="Green" Offset="1" />

The C# version

In case you are curious about what that XAML would look like if it was written in C#, here's the translation:

Button b = new Button();
b.Content = "Click Me";
b.Click += this.OnButtonClick;
LinearGradientBrush lgb = new LinearGradientBrush();
lgb.GradientStops.Add( new GradientStop( Colors.Yellow, 0 ) );
lgb.GradientStops.Add( new GradientStop( Colors.Green, 1 ) );
b.Background = lgb;

Markup extensions

The XAML parser also knows how to work with a special construct known as the "markup extension." Markup extensions allow you to compactly configure objects and reference other objects defined elsewhere in the application. They are used when setting a property on an object, either via an XML attribute or the property element syntax. Markup extensions are used for things such as specifying a null value, declaring an array, referencing an object held in a resource dictionary, binding one property to another, and much more.

The following XAML is roughly equivalent to the example shown previously (with a few minor changes):

    <LinearGradientBrush x:Key="FunkyBrush">
      <GradientStop Color="Yellow" Offset="0" />
      <GradientStop Color="Green" Offset="1" />
  <Button Background="{StaticResource FunkyBrush}">Click Me</Button>

Notice that the Button's Background property is set, via an XML attribute, to {StaticResource FunkyBrush}. When an attribute is set to a value which begins with { and ends with }, then a markup extension is being used.

In this case the StaticResourceExtension class is being used to reference a LinearGradientBrush stored in the Grid's resource dictionary. (Note: Grid is a layout panel in WPF, not a tabular data presentation control like you might expect.)

Code-behind files

XAML is compiled down into a class. Unless you specify the class name it should use, the compiler will generate a class name for you. However, when you apply the x:Class attribute to the root XML element in a XAML file, you can create a partial class in C# or VB.NET which will be merged with the XAML partial. This is how you can associate behavior with the layout and visuals declared in XAML.

For example, in the demonstration above we created a Button in XAML and assigned an event handling method to its Click event. The OnButtonClick method would be defined in the code-behind file which contains another part of the class associated with the partial class generated by the XAML.

Let's suppose that the Button we've been discussing is in a Window subclass called MyWindow. Here would be the code-behind file (MyWindow.xaml.cs):

public partial class MyWindow : Window
 public MyWindow()
 void OnButtonClick( object sender, RoutedEventArgs e )
  MessageBox.Show( "Click me again.  That felt good." );

How the WPF Horse Race uses XAML

The WPF Horse Race application is almost entirely written in XAML. The application uses three C# files: the code-behind for the main Window, a file for the RaceHorse class, and another which contains some value converters (more on those in the article about data binding). The rest of the application is all in XAML.

I encourage you to explore the WPF Horse Race source files and check out what XAML looks like when it's being used to create a real program (as opposed to just a simple demonstration of it). The rest of the articles in this series will examine how that entire application works, but there is no substitute for just digging into the source files now and exploring how it works on your own.

External links



General WPF Tips


  • April 1, 2007 - Created the article.
  • April 3, 2007 - Removed superfluous ColumnDefinitions from the Grid in RaceHorseDataTemplate.xaml and updated the demo project download file.
  • April 18, 2007 - Fixed an incorrect statement about markup extensions. Originally I asserted that they are only used in conjunction with XML attributes, but they can be used with the property element syntax, as well.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Josh Smith
Software Developer (Senior) Cynergy Systems
United States United States
Josh creates software, for iOS and Windows.

He works at Cynergy Systems as a Senior Experience Developer.

Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.

Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.

Check out his Advanced MVVM[^] book.

Visit his WPF blog[^] or stop by his iOS blog[^].

You may also be interested in...

Comments and Discussions

GeneralSample code now on Git Hub Pin
Igor Dvorkin24-Oct-15 6:18
memberIgor Dvorkin24-Oct-15 6:18 
Questionunclear Pin
Member 1179891215-Jul-15 17:41
memberMember 1179891215-Jul-15 17:41 
QuestionAdditional Information - Voted 4 Pin
Raja Chandrasekaran14-Jul-14 15:02
memberRaja Chandrasekaran14-Jul-14 15:02 
GeneralMy vote of 5 Pin
Mehradzie27-Apr-14 14:46
professionalMehradzie27-Apr-14 14:46 
GeneralMy vote of 5 Pin
aymkam2-Apr-14 5:10
memberaymkam2-Apr-14 5:10 
Bugsuggest a correction in excerpt Pin
Member 1039159510-Nov-13 1:10
memberMember 1039159510-Nov-13 1:10 
GeneralMy vote of 5 Pin
DeniskoS9-Sep-13 4:37
memberDeniskoS9-Sep-13 4:37 
GeneralMy vote of 5 Pin
Raja Sekhar S31-May-13 2:10
professionalRaja Sekhar S31-May-13 2:10 
GeneralMy vote of 5 Pin
StefanJG30-Nov-12 3:23
memberStefanJG30-Nov-12 3:23 
GeneralThanks! Pin
TMBCoder29-Nov-12 3:47
memberTMBCoder29-Nov-12 3:47 
GeneralMy vote of 4 Pin
Stephane Halimi24-Nov-12 7:37
memberStephane Halimi24-Nov-12 7:37 
GeneralMy vote of 5 Pin
Farhan Ghumra27-Aug-12 21:51
memberFarhan Ghumra27-Aug-12 21:51 
GeneralMy vote of 5 Pin
José Francisco Bianchi Filho19-Jul-12 17:43
memberJosé Francisco Bianchi Filho19-Jul-12 17:43 
Bugrotation degree Pin
samozvanec2-Jul-12 6:28
membersamozvanec2-Jul-12 6:28 
GeneralMy vote of 4 Pin
TeaTime13-Mar-12 2:31
memberTeaTime13-Mar-12 2:31 
QuestionA Query abt WPF Pin
Member 850540620-Dec-11 19:47
memberMember 850540620-Dec-11 19:47 
QuestionError Pin
marshall_donuts19-Dec-11 6:19
membermarshall_donuts19-Dec-11 6:19 
AnswerRe: Error Pin
Richard MacCutchan14-Mar-12 3:50
mvpRichard MacCutchan14-Mar-12 3:50 
See here[^].
Unrequited desire is character building. OriginalGriff
I'm sitting here giving you a standing ovation - Len Goodman

GeneralMy vote of 4 Pin
Aditya_Srivastava12-Dec-11 19:00
memberAditya_Srivastava12-Dec-11 19:00 
GeneralMy vote of 5 Pin
MZwahlen1-Dec-11 0:17
memberMZwahlen1-Dec-11 0:17 
GeneralMy vote of 5 Pin
Spike_javi25-Jul-11 9:40
memberSpike_javi25-Jul-11 9:40 
GeneralMy vote of 5 Pin
swayson23-Dec-10 5:37
memberswayson23-Dec-10 5:37 
GeneralIssue for open WpfHorseRace Pin
Member 44498445-Oct-10 2:34
memberMember 44498445-Oct-10 2:34 
QuestionWhat 'Project type' is this? Pin
FrankGallagher17-Aug-10 5:57
memberFrankGallagher17-Aug-10 5:57 
GeneralMy vote of 1 Pin
doanduychinh10-May-10 19:14
memberdoanduychinh10-May-10 19:14 
GeneralThanks for article!!! Pin
Member 29744576-May-10 0:35
memberMember 29744576-May-10 0:35 
GeneralVery Good Pin
Abhishek Sur8-Nov-09 10:15
memberAbhishek Sur8-Nov-09 10:15 
Generalthanks Pin
zhujinlong1984091327-Aug-09 2:53
groupzhujinlong1984091327-Aug-09 2:53 
GeneralJ.S. Bach! Pin
Clay Shannon18-Jun-09 10:02
memberClay Shannon18-Jun-09 10:02 
Generalgreat article! Pin
sth_Weird17-Jun-09 4:03
membersth_Weird17-Jun-09 4:03 
GeneralWhy does the app change my screen resolution when run in VS2008 Pin
CrashMigo1-Dec-08 5:46
memberCrashMigo1-Dec-08 5:46 
GeneralRe: Why does the app change my screen resolution when run in VS2008 Pin
Josh Smith1-Dec-08 5:48
mvpJosh Smith1-Dec-08 5:48 
GeneralRe: Why does the app change my screen resolution when run in VS2008 Pin
CrashMigo1-Dec-08 5:52
memberCrashMigo1-Dec-08 5:52 
GeneralHi Josh Pin
Santhapur7-Aug-08 5:20
memberSanthapur7-Aug-08 5:20 
GeneralRe: Hi Josh Pin
Josh Smith7-Aug-08 5:44
mvpJosh Smith7-Aug-08 5:44 
GeneralRe: Hi Josh Pin
Santhapur7-Aug-08 5:46
memberSanthapur7-Aug-08 5:46 
GeneralRe: Hi Josh Pin
Josh Smith7-Aug-08 5:48
mvpJosh Smith7-Aug-08 5:48 
GeneralRe: Hi Josh Pin
Santhapur7-Aug-08 5:52
memberSanthapur7-Aug-08 5:52 
GeneralWonderful. Pin
MAHorn28-Jul-08 11:44
memberMAHorn28-Jul-08 11:44 
GeneralRe: Wonderful. Pin
Jeremiah Morrill28-Jul-08 13:27
memberJeremiah Morrill28-Jul-08 13:27 
GeneralRe: Wonderful. Pin
MAHorn29-Jul-08 3:34
memberMAHorn29-Jul-08 3:34 
GeneralRe: Wonderful. Pin
Jeremiah Morrill29-Jul-08 16:54
memberJeremiah Morrill29-Jul-08 16:54 
General[Message Removed] Pin
nompel20-Sep-08 16:01
membernompel20-Sep-08 16:01 
Questioncan we develop an application in WPF Pin
Member 36657534-Jul-08 0:17
memberMember 36657534-Jul-08 0:17 
AnswerRe: can we develop an application in WPF Pin
Josh Smith4-Jul-08 4:29
mvpJosh Smith4-Jul-08 4:29 
Question'Specified cast is not valid.' when looking at the XAMl Pin
Member 237557727-May-08 9:55
memberMember 237557727-May-08 9:55 
AnswerRe: 'Specified cast is not valid.' when looking at the XAMl Pin
Josh Smith27-May-08 9:58
mvpJosh Smith27-May-08 9:58 
GeneralRe: 'Specified cast is not valid.' when looking at the XAMl Pin
Ray Veenema25-Aug-09 6:20
memberRay Veenema25-Aug-09 6:20 
GeneralXAML typo Pin
Richard Albury5-May-08 9:16
memberRichard Albury5-May-08 9:16 
GeneralRe: XAML typo Pin
Josh Smith5-May-08 10:01
mvpJosh Smith5-May-08 10:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 19 Apr 2007
Article Copyright 2007 by Josh Smith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid