An introduction to Windows Presentation Foundation

This article was originally published in VSJ, which is now part of Developer Fusion.
This article provides an introduction to Windows Presentation Foundation (WPF), formerly code-named ‘Avalon’, and will hopefully go some way to answering questions about what it is and why you might want to use it. Please note that WPF is currently in at an early beta release stage, so everything herein is subject to change.

Background

Occasionally, Microsoft announces a new version of the core Windows programming API. In fact, there have only been two major releases of this API to date: Win16 and Win32. And then, during the Professional Developer Conference in 2003, Microsoft announced the name for the next incarnation of the Windows API: WinFX. What made this particular announcement so significant was that, for the first time, the Windows API was going to be based on managed .NET code.

As part of this announcement, Microsoft previewed two core parts of the WinFX API: Avalon and Indigo. These have now been renamed as part of the changes for the next-generation Windows client, Windows Vista (formerly codenamed ‘Longhorn’). Indigo has become Windows Communication Foundation, and as its name suggests, it represents the part of the API that deals with an application’s communication services such as its use of transactions, MSMQ and services (including Web Services). Avalon has become Windows Presentation Foundation, and we will be focusing exclusively on this throughout the article. The third part, WinFS, is responsible for working with data, and will only be released in beta by the time that Windows Vista ships.

An overview of the WinFX API structure can be seen in Figure 1.

Figure 1
Figure 1: WinFX API structure

So what is Windows Presentation Foundation?

Windows Presentation Foundation (WPF) can be summarised as the unified presentation subsystem in WinFX. In simple terms, WPF is responsible for the user interface (UI) of the application. It is logically divided into two parts: an engine for rendering output, and a framework containing the core types needed by developers in today’s media-rich applications.

Why do we need another UI framework?

Many developers will be wondering why they need yet another UI programming environment. After all, there is Windows Forms for “smart client” applications, and ASP.NET 2.0 (and AJAX) for writing web-based applications. So let’s look at some of the motivations behind WPF.

As a start point, the classics Windows Forms style of application looks dated, especially in comparison with the richness of the interfaces witnessed in today’s web applications. Similarly, Windows Forms applications are constrained in their behaviour as a result of their dependence on underlying Window control types, which leave little scope for customisation and styling.

Machine hardware has also improved since the initial GDI and GDI+ libraries were released. These are principally two-dimensional bitmap (or raster) libraries, which use software to render graphics. Bitmap graphics also tend to suffer from jaggedness when scaled. Nowadays, most PCs ship with intensely powerful graphics adapters that are optimised in hardware for rendering via DirectX. Additionally, display devices in particular are beginning to ship with much higher dots per inch (DPI) values. WPF therefore uses vector-based, highly accurate and scalable rendering that fully exploits the capabilities of the hardware, without requiring rework on the part of the developer. It also has a full 3D modelling and material system built in, so expect to see an increasing number of 3D user interfaces in applications.

An increasing number of applications use sound, streaming video, speech or animation to enhance the capabilities of the application. For example, a hospital might implement a system that allowed doctors to record diagnoses verbally and store these alongside supporting images from X-ray or MRI scans, making them easier to share with other doctors. WPF has extensive support for creating such media-rich applications, which will be covered in a later article.

Users are also very familiar with the concept of navigating through applications, largely down to their experience with ubiquitous web browsers. This seemingly random navigation model is not well supported by traditional Windows applications. WPF supports both declarative and programmatic navigation between pages within an application, providing a seamless browsing experience.

Users also need to view and print documents. Windows Forms is particularly poor at rendering document flow, especially as the form factor of the device and/or the size of the viewing window changes. There is also a loss of fidelity when printing web pages from a browser, as I’m sure that most of you have discovered! WPF addresses this by supporting XML Paper Specification documents, and comes supplied with rich document viewing controls. XML Paper Specification (XPS, formerly known as ‘Metro’) is, amongst other things, the new native print format for Windows Vista.

Developers need to be able to easily extend and modify the controls that make up the user interface. This has always been possible in Windows, but the amount of work required to adjust, say, a Button’s look is often out of proportion with developing the rest of the UI. WPF has rich styling abilities, similar in concept to those found in CSS, which lets you change the look and feel of controls declaratively.

Another aspect of modern applications is the ease with which data can be displayed to the user. Windows Forms has support for data binding, but it requires considerable effort to produce, say, an application that presents mixed data such as a graphics, media and text.

Finally, application deployment and security has always been somewhat challenging. WPF gains the benefits of the security within the CLR as well as the operating system. It also uses ClickOnce deployment as a primary means of distribution, with all of the benefits that this provides, including running code under the restricted permission sets granted to Internet applications by the CLR.

WPF is a client-side technology

There is one thing that must be clearly understood: WPF is about writing the next generation of client application. All of your WPF code will be executing on the client, although you can, of course, use web services to communicate with a server.

You are executing managed code on the client, so the WinFX runtime components, including the Framework Class Library, must be installed on the client machine.

Avalon, AERO and XAML

Over the past couple of years there has been some confusion with the three terms above. Let’s address this now.

Hopefully by now you have a clear understanding of what Avalon, or rather WPF, really is. AERO, or more properly Windows Vista User Experience, is a set of user experience guidelines that govern the look and feel of applications that run on Windows Vista. Obviously, these guidelines cover mundane matters such as ensuring the application is accessible, reacts to the individual user’s settings etc., as well as looking at more exciting aspects such as (and I quote Microsoft here) “the feelings [the application] evokes”.

And then there’s XAML: eXtensible Application Markup Language. As its name suggests, XAML is an XML-based language used for the declarative creation of WPF applications. This will be covered a little later in this article.

Platform support

Now it might appear from the previous sections that WPF is restricted to Windows Vista, but this is not the case. Windows XP and Windows Server 2003 will also be able to run WPF applications, but older versions of Windows will not. Does this make WPF a viable target application environment for your application? Only you can answer that, but it will depend on whether your organisation (or target customer) has already upgraded to XP, or whether you need to support legacy platforms.

Working with WPF today

At the time of writing, WPF is in its first public beta release. So what do you need to write a WPF application, which is what we’ll be covering below? To start with, you need to have the following installed:
  1. A supported platform as described above.
  2. The WinFX Runtime Components, Beta 1. These can be downloaded.
  3. The WinFX SDK, Beta 1. This can be installed over the web, or you can download an ISO image.
Of course, whilst it is possible to code your WPF applications using Notepad or even the XAMLPad application that ships with the SDK, you will almost certainly want to be using Visual Studio 2005, especially as the majority of the samples were written using this IDE. The current Beta 1 of the SDK works with Visual Studio 2005 Beta 2, and to make it easier to write XAML code, you should download the Microsoft Visual Studio Extensions for WinFX Beta 1. These extensions provide IntelliSense support for XAML, project templates for the different application types and integrated SDK help.

Note that you can also write WPF applications using the relevant Express version of Visual Studio 2005.

Of course, it should really go without saying that these are beta products, and you should therefore be aware of the disclaimers and limitations before you install the software on any machines. You also need to be aware that with the current beta version you have to manually configure IIS to serve up WPF applications for ClickOnce deployment. For more details on how to do this, search for the article Configure a Web Server to Deploy “Avalon’’ Applications in the WinFX documentation.

So with the background information dealt with, let’s dive into writing a WPF application.

The WPF application model

There are a number of decisions to make before you leap in and start coding a WPF application. These affect the deployment and the style of the application.

In keeping with all ClickOnce deployed applications, you have some choices to make with regards to the type of application that you develop. WPF supports two types of applications: Express and Installed. The key differences and benefits of each type are summarised below:

Express applications
These are hosted by the browser; to run an Express application, the user clicks a link on a web page and the code for the application is downloaded and cached on their machine. This means that the application runs inside a security sandbox with permissions limited to those of the Internet zone, don’t appear in Control Panel’s Add/Remove Programs Applet, and don’t get installed in the users’ Start menu.

The main constraint on the user interface is that you cannot display “dialog boxes” (secondary windows) from an Express application. You can navigate between pages, but only within a single on-screen window. Similarly, you cannot touch the file system except through the Isolated Storage mechanism built into the .NET Framework, nor can you do very much with Windows Communication Foundation (Indigo).

Note that due to the limitations of the beta, certain controls don’t currently work (well) in Express applications. The most notable of these is the lack of support for the DocumentViewer control, and thus the flexible display of documents is somewhat restricted.

Figure_2 shows an example of an Express application being downloaded within the browser.

Figure 2
Figure 2: Downloading an Express Application

Installed applications
These, on the other hand, are downloaded and installed onto the user machine. They don’t run inside the browser and can be granted full trust. They also integrate with the Add/Remove Programs applet and the users’ Start menu. An Installed application can be deployed either using ClickOnce or you can use Windows Installer (.msi) technology; the latter option affords even greater interaction with the client, such as registering COM components and so forth.

There are also three styles of WPF application: Navigation, Window and Document applications.

  • Navigation applications typically consist of one or more pages within the application, in much the same way that a web application might have multiple .aspx pages. The user typically navigates through the application by clicking buttons or links, with each page containing its own UI. Note that Express applications must be Navigation applications.
  • Window applications follow a model similar to a Windows Forms application. A Window application can display secondary pop-up windows. These applications will typically have quite a lot of procedural code associated with them to respond to user actions.
  • Document applications, on the other hand, will have no procedural code. Instead, the application is merely presenting information to a user, in much the same way that users read PDF content.

The WPF programming model: XAML

One of the common misconceptions is that all WPF applications have to be written in XAML. This is certainly not the case, but there are considerable advantages to creating UIs declaratively using structured XML. For a start, the object model for a WPF application is hierarchical in nature, with a single window element that has a single root panel element, which is used to control the layout of the controls that it contains. All content and controls are then nested within the hierarchy, as depicted in Figure_3.

Figure 3
Figure 3: Object hierarchy

As you can see, XML (and thus XAML) is the obvious syntax of choice for defining such a tree structure. In comparison, whereas XAML directly maps onto this model, programmatic code (C#, Visual Basic, etc) has to explicitly add items and create the tree structure.

So let’s look at a simple HelloWorld sample in both XAML and C# to highlight the differences:

XAML

<Window
xmlns=”http://schemas.microsoft.com/
	winfx/avalon/2005”
xmlns:x=”http://schemas.microsoft.com/
	winfx/xaml/2005”
	Text=”Hello World”>
	<Grid Background=”VerticalGradient
		Wheat White”>
		<TextBlock FontFamily=”Tahoma”
			FontSize=”32”
			HorizontalAlignment=”Center”
			VerticalAlignment=”Center”>
			Hello World
		</TextBlock>
	</Grid>
</Window>
C#
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace HelloWorld {
	public partial class MyApp :
			Application {
		void AppStartingUp(
			object sender,
		StartingUpCancelEventArgs e ) {
			MainWindow mw =
				new MainWindow();
			mw.Show();
		}
	}
	public class MainWindow : Window {
		public MainWindow() {
			Grid g = new Grid();
			g.Background =
				new LinearGradientBrush(
				Colors.Wheat,
				Colors.White, 90.0 );
			TextBlock tb =
				new TextBlock();
			tb.TextContent =
				“Hello World”;
			tb.FontFamily =
				new FontFamily(“Tahoma”);
			tb.FontSize = 32;
			tb.HorizontalAlignment =
			HorizontalAlignment.Center;
			tb.VerticalAlignment =
				VerticalAlignment.Center;
			Text = “Hello World”;
			g.Children.Add( tb );
			Content=g;
		}
	}
}
Now, given that both these pieces of code produce the same output, shown in Figure_4, I know which of the two languages I would want to be using to create the user interface!

Figure 4
Figure 4: Hello World

You can also see from the XAML sample how the elements map onto the objects in the tree, whilst the attributes are used to set the objects’ properties, such as the alignment of the TextBlock.

XAML comes into its own when you move away from the trivial single element hierarchy that we had in the previous example. By way of example, let’s consider how you might style all of the TextBoxes within an application to use a specific font and text size. With XAML this can be achieved by creating a style as part of the resources for the application, as shown in the code below:

<NavigationApplication.Resources>
	<Style TargetType=”{x:Type TextBox}”>
		<Setter Property=”FontFamily” Value=”Arial” />
		<Setter Property=”FontSize” Value=”18” />
	</Style>
</NavigationApplication.Resources>
The style will then be applied to all controls of the appropriate type from that point down in the hierarchy. Of course, individual controls can override these default settings. This styling (and resource) mechanism can be used at different levels of the hierarchy, so for example all of the Buttons in a single Grid can be styled using a .Resources block for that specific Grid.

By now it should be easy to see that XAML is the preferred choice for designing the UI content for your WPF applications, primarily due to the ease with which you can set properties and styles for the visual elements, and the natural mapping of the object model onto the XAML elements.

XAML is also extensible to support your own custom elements, so you are not constrained in the same way that, say, an HTML developer is to a predefined set of visual elements.

Laying out WPF pages

As you saw in Figure_3, the controls are organised in a simple hierarchical tree that represents the visual elements. In XAML, the parent/child relationship of the elements is immediately obvious from the XML hierarchy. However, user interfaces rarely consist of trees. Normally, you need to position visual elements either explicitly or using docking / anchoring strategies.

The object model for WPF incorporates elements that are specifically designed to help you lay out your UI, using containers that are derived from the base Panel class. Table 1 lists the most common layout elements and describes their typical usage.

Table 1: Common Panel types in WPF
Canvas Allows absolute positioning of controls within a UI.
DockPanel A panel that is used to enforce docking of its child elements to an edge or area of a page.
Grid A grid combines features from both the Canvas and the Table. The Grid is ideal for designing dialog boxes.
StackPanel This control is used to build stacks of elements, much like stacking boxes one on top of the other (or next to each other if the orientation is horizontal).
You can see an example of a layout with a GridPanel in Figure_5.

Figure 5
Figure 5: Layout with a GridPanel

Note that the red lines are there for you to see the different Grid cells, and are not seen by the user.

Control support

WPF has all of the usual controls that you would expect, such as Buttons, ListBoxes, Menus and so forth. As most of us are familiar with the typical user interface controls, I won’t go into them in detail here: you can find this information in the WinFX SDK. However, there is one common underlying principle when using these controls: they’re easy to work with! To give you an idea of the simplicity of the programming model, let’s take a quick look at a common and tedious problem in Windows applications: scrollable applications.

As a Windows Forms programmer, you might have used the AutoScroll/ AutoScrollMinSize properties to support scrolling, which I’ll agree wasn’t too difficult to accomplish. XAML and the WPF controls simplify this even further, as shown in the XAML below:

<ScrollViewer>
	<Grid>
		<!- Grid content here ->
	</Grid>
</ScrollViewer>
As you can see, the idea of scrolling is contained within a separate element. Therefore, you can add “scrollability” to any child control, although the idea of scrollbars on a Button takes some getting used to.

Working with events

Whether it is updating the state of a control as the user enters text, or simply responding to the click of a Button, most applications are interactive. Now, as with much in WPF, there are many ways to work with the UI and events. For example, take a look at the following XAML:
<Window
xmlns=”http://schemas.microsoft.com/
	winfx/avalon/2005”
xmlns:x=”http://schemas.microsoft.com/
	winfx/xaml/2005”
	Text=”HelloWorld”
	>
	<Window.Resources>
		<Style TargetType=
			”{x:Type Button}”>
			<Setter Property=
				”Background”
				Value=
	”VerticalGradient White Green” />
			<Setter Property=”Margin”
				Value=”5,5,5,5” />
			<Style.Triggers>
				<Trigger
				Property=”IsMouseOver”
				Value=”True”>
					<Setter
					Property=”Background”
					Value=”Silver” />
				</Trigger>
			</Style.Triggers>
		</Style>
	</Window.Resources>
	<StackPanel
		Background=”VerticalGradient
			White #80FFFF00”>
		<StackPanel
			Orientation=”Horizontal”
			Height=”50”
			VerticalAlignment=”Top”
			Background=”VerticalGradient
				White Silver”>
			<Button>Option 1</Button>
			<Button>Option 2</Button>
			<Button>Option 3</Button>
			<Button>Option 4</Button>
		</StackPanel>
		<TextBlock
			HorizontalAlignment=”Center”
			Margin=”0,30,0,30”>
			Hover over a button to see
			what happens!
		</TextBlock>
	</StackPanel>
</Window>
I have emboldened the style triggers in the code above, as this section of the style section for the Button will implement a “rollover” effect, setting the appropriate Button object’s background to Silver. When the mouse moves off the Button, its background will be reset to the default white/green gradient fill. You can see the effect of this code in Figure_6.

Figure 6
Figure 6: A simple mouse rollover

Of course, you’ll probably want to write real event handlers. This can all be done in XAML, as demonstrated here:

<Button Click=”OptionClicked”>
	Option 1</Button>
...
<TextBlock Name=”theText” ...>
	Hover over a button to see
		what happens!
</TextBlock>
...
<x:Code>
	<![CDATA[
	private void OptionClicked(
		object sender,
		RoutedEventArgs e )
	{
		theText.TextContent =
			“It worked!”;
	}
	]]>
</x:Code>
There are a few points of note in this code, namely:
  1. The Button’s Click event is connected much like it is done with an event in ASP.NET. However, you must remember that WPF is purely a client-side technology, and all events are handled wherever the application is running.
  2. The code itself, marked with the <x:Code> element, has to lie within a <![CDATA[]]> block, because it is obviously not well formatted XML.
  3. Interacting with controls is easy in code. Simply name the control, as has been done here with the TextBlock, and you can access it programmatically.
  4. Those of you familiar with the typical Windows Forms Button’s (or ASP.NET server control Button’s) Click event will notice that the signature has changed for the event handler. This is because events in WPF are bubbled up through the object tree, enabling them to be handled at a higher level. However, this requires more information about the originating control and the event to be propagated.
Now I don’t know about you, but I’m not sure that I want to be writing event handling code in my XAML files. I actually like the code/view separation model of ASP.NET 2.0 and, to a lesser extent, the one from Windows Forms 2.0. So can I use this form of structure in my WPF applications when working with XAML?

The answer to this is a resounding yes! With the advent of Visual Studio 2005, the compilers now support partial classes. The primary motivation for partial classes is to allow designers (human or electronic) to write a part of the class in one language, and let developers write the programmatic parts in another language. Therefore, when writing WPF applications in a mixture of XAML and C# or Visual Basic 2005, your code will look something like this:

MainPage.xaml
<Window
xmlns=”http://schemas.microsoft.com/
	winfx/avalon/2005”
xmlns:x=”http://schemas.microsoft.com/
	winfx/xaml/200”
	x:Class=”HelloWorld.MainWindow”
	>
		...
	<Button
	Click=”OptionClicked”>...</Button>
</Window>

MainPage.cs
namespace HelloWorld {
	public partial class MainWindow :
		Window {
		private void OptionClicked(
			object sender,
			RoutedEventArgs e )
		{
			...
		}
	}
}
If you build your applications using Visual Studio 2005 (and I strongly recommend that you do), then you will be working with this code behind model by default. The only downside to using XAML today is that there is no visual designer support inside Visual Studio 2005, but this is obviously something that will be remedied over the coming months.

Summary

At this point, you will have realised that I haven’t looked at animation, media, 3D, speech, data binding or all of the other rich aspects that WPF has to offer. That’s because these subjects will be covered in later articles. For now, then, I’ll simply summarise what we’ve looked at so far.

WPF is the next-generation client presentation technology for Windows, and is part of the WinFX API. There are two deployment strategies, Express and Installed applications; with three styles of application: Navigation, Window and Document.

The programming model available is either purely declarative using XAML, programmatic with a .NET language of your choice, or a mixture of the two using partial classes. The use of XAML fits the object model and visual element tree that is used by the WPF engine very neatly, making XAML the natural choice of language for designing your UI.

WPF will be available on Windows XP, Windows Server 2003 and Windows Vista.


Dave Wheeler is a principal technologist at QA, one of the UK’s leading IT training companies, where he specialises in .NET and other Microsoft development technologies. Read Dave Wheeler’s blog.

You might also like...

Comments

About the author

Dave Wheeler United Kingdom

Dave Wheeler is a freelance instructor and consultant who specialises in .NET application development. He’s a moderator on Microsoft’s ASP.NET and Silverlight forums and is a regular speaker at ...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Programs must be written for people to read, and only incidentally for machines to execute.”