Introducing Windows Presentation Foundation

 

David Chappell
Chappell & Associates

September 2006

Applies to:
   Windows Vista
   Windows Presentation Foundation
   Microsoft .NET Framework 3.0

Summary: The primary goal of Windows Presentation Foundation (WPF) is to help developers create attractive and effective user interfaces. Learn how the WPF unified platform helps make designers active participants in creating user interfaces, and provides a common programming model for standalone and browser applications. (34 printed pages)

Contents

Describing Windows Presentation Foundation
   Illustrating the Problem
   Addressing the Problem: What Windows Presentation Foundation Provides
Using Windows Presentation Foundation
   The Technology of Windows Presentation Foundation
   Applying Windows Presentation Foundation
Tools for Windows Presentation Foundation
   For Developers: Visual Studio
   For Designers: Expression Interactive Designer
Windows Presentation Foundation and Other Microsoft Technologies
   Windows Presentation Foundation and Windows Forms
   Windows Presentation Foundation and Win32/MFC
   Windows Presentation Foundation and Direct3D
   Windows Presentation Foundation and AJAX/"Atlas"
   Windows Presentation Foundation and "WPF/E"
Conclusion
About the Author

Describing Windows Presentation Foundation

By definition, technical people care most about technology. Many software professionals are far more interested in how an application works than in how it interacts with its users. Yet those users—who are, after all, the ones paying for all of this—care deeply about user interfaces. An application's interface is a major part of the complete user experience with that software, and to its users, the experience is the application. Providing a better user experience through a better interface can improve productivity, help create loyal customers, increase sales on a Web site, and more.

Once happy with purely character-based interfaces, users have now become accustomed to graphical interfaces. Yet the requirements for user interfaces continue to advance. Graphics and media have become more widely used, and the Web has conditioned a generation of people to expect easy interaction with software. The more time people spend interacting with applications, the more important the interfaces to those applications become. To keep up with increasing expectations, the technology used to create user interfaces must also advance.

The goal of Windows Presentation Foundation (WPF) is to provide these advances for Windows. Included in version 3.0 of the Microsoft .NET Framework, WPF allows building interfaces that incorporate documents, media, two- and three-dimensional graphics, animations, Web-like characteristics, and much more. Like everything else in the .NET Framework 3.0, WPF will be available for Windows Vista, Windows XP, and Windows Server 2003, and it's scheduled to be released when Windows Vista ships. This paper introduces WPF, describing its various parts. The goal is to make clear the problems this technology addresses, then survey the solutions that WPF provides.

Illustrating the Problem

Suppose a hospital wants to create a new application for examining and monitoring patients. The requirements for this new application's user interface might include the following:

  • Displaying images and text about the patient.
  • Displaying and updating two-dimensional graphics showing the patient's vital signs, such as heart rate and blood pressure.
  • Providing three-dimensional views and overlays of patient information.
  • Presenting video of ultrasounds and other diagnostics, perhaps allowing physicians and nurses to add annotations.
  • Allowing hospital staff to read and make notations on documents describing the patient and her condition.
  • Running both as a Windows application, allowing full capability for hospital employees, and in a security-restricted Web browser application, allowing more limited access by remote physicians via the Internet.

These requirements are ambitious, but they're not unreasonable. User interfaces that present the right information in the right way at the right time can have significant business value. In situations such as the health care example described here, they can actually save lives. In less critical scenarios, such as on-line merchants or other consumer-oriented applications, providing a powerful user experience can help differentiate a company's offerings from its competitors, increasing both sales and the value of the firm's brand. The point is that many modern applications can benefit from providing interfaces that integrate graphics, media, documents, and the other elements of a modern user experience.

Building this kind of interface on Windows is possible with the technologies of 2006, but it's remarkably challenging. Some of the major hurdles are:

  • Many different technologies are used today for working with graphics, images, and video. Finding developers who are competent to work with these diverse technologies can be difficult and expensive, as is maintaining the applications they create.
  • Designing an interface that effectively presents all of this functionality to users is challenging. Professional designers are required—software developers don't have the right skills—but designers and developers face significant challenges in working together, especially with full-featured interfaces like the one described here.
  • Offering a full-featured interface as both a standalone Windows desktop application and a browser-hosted version would require building two separate implementations using two different sets of technology. The Windows desktop application would likely use Windows Forms and other native Windows technologies, while the browser-hosted application would use HTML and JavaScript. Two different groups of developers with two quite different skill sets are needed.

There's no inherent reason why creating powerful, modern user interfaces should be so complex. A common foundation could address all of these challenges, offering a unified approach to developers while letting designers play an important role. As described next, this is exactly the intent of WPF.

Addressing the Problem: What Windows Presentation Foundation Provides

Three aspects of what WPF provides stand out as most important. They are: a unified platform for modern user interfaces, the ability for developers and designers to work together, and a common technology for Windows and Web browser user interfaces. This section describes each of these three.

A Unified Platform for Modern User Interfaces

In a pre-WPF world, creating a Windows user interface like the one described earlier would require using several different technologies. The table below summarizes the situation.

  Windows Forms PDF Windows Forms/
GDI+
Windows Media Player Direct3D WPF
Graphical interface, e.g., forms and controls X         X
On-screen documents X         X
Fixed-format documents   X       X
Images     X     X
Video and audio       X   X
Two-dimensional graphics     X     X
Three-dimensional graphics         X X

To create the forms, controls, and other typical aspects of a Windows graphical user interface, a developer would most likely choose Windows Forms, part of the .NET Framework. If the interface needs to display documents, Windows Forms has some support for on-screen documents, while fixed-format documents might use Adobe's PDF. For images and two-dimensional graphics, that developer will use GDI+, a distinct programming model that is also accessible via Windows Forms. To display video and audio, he might rely on Windows Media Player, and for three-dimensional graphics, he'll use Direct3D, a standard part of Windows.

This complicated situation exists solely for historical reasons. No one would argue that it makes much sense. What does make sense is to provide a single unified solution: WPF. Developers creating applications for machines with WPF installed will likely use it to address all the areas listed above. After all, why not use one coherent foundation for creating user interfaces rather than a diverse collection of independent technologies?

WPF doesn't replace everything on this list, of course. Windows Forms applications will continue to have value, and even in a WPF world, some new applications will continue to use Windows Forms. (It's worth noting that WPF can interoperate with Windows Forms, something that's described in more detail later in this paper.) Windows Media Player continues to have an independent role to play, and PDF documents will continue to be used. Direct3D also remains an important technology for games and some other kinds of applications. (In fact, WPF itself relies on Direct3D for all rendering.)

Yet by providing a broad range of functionality in a single technology, WPF can make creating modern user interfaces significantly easier. To get a sense of what this unified approach allows, here's a typical screen that a WPF-based version of the health care application described above might present to a user:

Aa663364.introducingwpf1(en-us,MSDN.10).gif

Figure 1. A WPF interface can combine images, text, 2D and 3D graphics, and more.

This screen contains text and images along with both two- and three-dimensional graphics. All of this was produced using WPF—the developer doesn't need to write code that uses specialized graphics technologies such as GDI+ or Direct3D. Similarly, WPF allows displaying and perhaps annotating video, such as the ultrasound feed shown below.

Aa663364.introducingwpf2(en-us,MSDN.10).gif

Figure 2. A WPF interface can include video, allowing the user to make text annotations.

WPF also allows displaying documents in a readable way. In the hospital application, for instance, a physician might be able to look up notes about a patient's treatment or access current medical research on a relevant topic. Again, the physician might be able to add annotations as the screen below shows.

Aa663364.introducingwpf3(en-us,MSDN.10).gif

Figure 3. WPF interface can display multi-column documents, including annotations.

Notice that the document is displayed in readable columns and that the user can move through it a page at a time rather than by scrolling. Improving on-screen readability is a worthy aim, and it's an important goal of WPF. Useful as on-screen documents are, however, fixed-format documents can sometimes be the right choice. Because they look the same on screen and on a printer, fixed-format documents provide a standard look in any situation. To define this type of document, Microsoft has created the XML Paper Specification (XPS). WPF also provides a group of application programming interfaces (APIs) that developers can use to create and work with XPS documents.

Yet creating modern user interfaces means more than just unifying what were once diverse technologies. It also means taking advantage of modern graphics cards, and so WPF exploits whatever graphics processing unit (GPU) is available on a system by offloading as much work as possible to it. Modern interfaces also shouldn't be constrained by the limitations of bit-mapped graphics. Accordingly, WPF relies entirely on vector graphics, allowing an image to be automatically resized to fit the size and resolution of the screen it's displayed on. Rather than creating different graphics for display on a small monitor and a big-screen television, the developer can let WPF itself handle this.

By unifying all of the technologies required to create a user interface into a single foundation, WPF can make life significantly simpler for the people who create those interfaces. By requiring those people to learn only a single environment, WPF can make creating and maintaining applications less expensive. And by making it straightforward to build interfaces that incorporate graphics, video, and more, WPF can improve the quality—and business value—of how users interact with Windows applications.

The Ability for Developers and Designers to Work Together

Providing a unified technology foundation for creating full-featured user interfaces is a good thing. Yet expecting developers to use this power wisely, creating comprehensible, easy-to-use interfaces, is probably asking too much. Creating good user interfaces, especially when they're as comprehensive as the hospital example just described, often requires skills that most software professionals just don't have. Even though many applications are built without them, the truth is that building great user interfaces requires working with professional interface designers.

But how can designers and developers work together? The way the two disciplines interact today is problematic. Most commonly, a designer uses a graphical tool to create static images of the screen layouts that an application should display. He then gives these images to the developer, whose job is to create the code that makes them real. Something that's easy for a designer to draw, however, might be difficult or impossible for a developer to implement. Technology limitations, schedule pressures, lack of skill, misunderstandings, or simple disagreement might prevent the developer from fully realizing the designer's vision. What's needed is a better way for members of these two interdependent disciplines to work together without compromising the quality of the interface.

To allow this, WPF introduces the eXtensible Application Markup Language (XAML). XAML defines a set of XML elements such as Button, TextBox, Label, and many more to define exactly how a user interface looks. XAML elements typically have attributes as well, allowing various options to be set. For example, this simple XAML snippet creates a red button containing the word "No":

<Button Background="Red">
 No
</Button>

Each XAML element corresponds to a WPF class, and each of that element's attributes has a corresponding property or event in the class. For example, the same red button could be produced with this C# code:

Button btn = new Button();
btn.Background = Brushes.Red;
btn.Content = "No";

If everything expressible in XAML is also expressible in code—and it is—what's the value of XAML? The answer is that building tools that generate and consume XML-based descriptions is much easier than doing the same thing with code. Because XAML offers a tool-friendly way to describe a user interface, it provides a better way for developers and designers to work together. The figure below illustrates the process.

Aa663364.introducingwpf4(en-us,MSDN.10).png

Figure 4. XAML helps designers and developers work together

A designer can specify how a user interface should look and interact using a tool such as Microsoft Expression Interactive Designer. Oriented entirely toward defining the look and feel of a WPF interface, this tool generates a description of that interface expressed in XAML. (While it might include a simple button like the example shown here, this description is in fact much more complex than the snippet above might suggest.) A developer then imports that XAML description into a tool such as Microsoft Visual Studio. Rather than recreating the interface from scratch based on static images produced by a designer, the interface definition itself is adopted wholesale. The developer then writes the code for the interface, such as event handlers, along with any other functionality the application requires. It's also possible to create styles that can be globally applied to an application's interface, allowing it to be customized as needed for different situations.

Enabling designers and developers work together like this reduces the translation errors that tend to occur when developers implement interfaces from designer-created images. It can also allow people in these two roles to work in parallel, with quicker iteration and better feedback. And because both environments use the same build system, a WPF application can be passed back and forth between the two development environments. More specialized tools for designing XAML-defined interfaces are also available, such as Electric Rain's ZAM 3D for creating three-dimensional interface elements.

Better user interfaces can increase productivity—they have measurable business value. Yet to create truly effective interfaces, especially in the multi-faceted world that WPF provides, designers must become first-class citizens in the process. A primary goal of XAML and the tools that support it is to make this possible.

A Common Technology for Windows and Web Browser User Interfaces

Creating effective user interfaces for Windows applications is important. Yet creating effective interfaces for Web-based applications is at least as important. By definition, these interfaces are provided by a Web browser, and the simplest approach is just to let the browser passively display whatever HTML it receives. More responsive browser interfaces provide logic running in JavaScript, perhaps using asynchronous JavaScript and XML (AJAX). The interface may even support animations, video, and more using Adobe's Flash Player or some other technology. Sometimes known as rich Internet applications, Web software that provides this kind of full-featured interface can significantly improve the user's experience. It can also add substantial business value by making a Web application more attractive to users.

Building this kind of interface has traditionally required using a completely different set of technologies from those used for a native Windows interface. Accordingly, developers commonly focus on one of these approaches: either you're a Windows interface developer or you're a Web interface developer. Yet for rich Internet applications that will be accessed from Windows, why should this dichotomy exist? There's no inherent reason why the same technologies can't be used for both native Windows interfaces and Web browser interfaces.

WPF allows this. A developer can create a XAML Browser Application (XBAP) using WPF that runs in Internet Explorer. In fact, the same code can be used to create a standalone WPF application and an XBAP. The screen below, for example, shows a financial services application running as a standalone Windows application. Like the hospital application shown earlier, this one mixes text, images, and various kinds of graphics. (This screen also illustrates the Windows Vista desktop, including gadgets such as the clock and the Aero theme that provides the semi-transparent borders around the application's window.)

Aa663364.introducingwpf5(en-us,MSDN.10).png

Figure 5. A financial services application can run as a standalone WPF application.

Here's how this interface looks running inside Internet Explorer as an XBAP:

Aa663364.introducingwpf6(en-us,MSDN.10).png

Figure 6. The same application can potentially run as an XBAP.

The interface is now framed by the browser rather than running in its own window, yet its functionality remains the same. The same code can also used in both cases, which decreases the amount of work required to address both kinds of interfaces. Using the same code also means using the same developer skills. Rather than forcing developers into the disjoint boxes of Windows interface developer or Web interface developer, WPF can break down those divisions, allowing the same knowledge to be used in both cases.

Another advantage of using the same technology for both Windows and Web interfaces is that an application's creator isn't necessarily forced to decide in advance what kind of interface the application should have. As long as the target clients meet the requirements for running XBAPs, an application can provide either (or both) a Windows and a Web interface using largely the same code.

Because an XBAP is downloaded on demand from a Web server, it faces more stringent security requirements than a standalone Windows application. Accordingly, XBAPs run in a security sandbox provided by the .NET Framework's code access security. XBAPs also run only on Windows systems with WPF installed and only with Internet Explorer versions 6 and 7. For applications that meet these requirements, however, rich Internet applications can now use the same foundation as standalone Windows applications.

Using Windows Presentation Foundation

Knowing what problems WPF addresses is useful, but having some understanding of how it addresses those problems is also useful. This section surveys the WPF technology itself, then looks at the different ways it's applied in Windows desktop applications, XBAPs, and XPS documents.

The Technology of Windows Presentation Foundation

Even though WPF offers a unified foundation for creating user interfaces, the technologies it contains can be examined in discrete, understandable parts. These parts include documents, images, graphics, animation, and more. All of them depend on WPF's basic application model, however, which is described next.

Application Model

Like other parts of the .NET Framework, WPF organizes its functionality into a group of namespaces, all contained in the System.Windows namespace. Whatever parts of this functionality it uses, the basic structure of every WPF application is much the same. Whether it's a standalone Windows application or an XBAP, the application typically consists of a set of XAML pages and code associated with those pages.

At its root, every application inherits from WPF's standard Application class. This class provides common services that are useful to every application. These include holding state that needs to be available to the entire application and providing standard methods such as Run, which starts the application, and Shutdown, which terminates it.

An Application object can be created with either XAML, via the Application element, or code, using the Application class. (This is true for virtually everything in WPF, but for simplicity, this paper always uses the XAML option.) Here's a simple XAML illustration:

<Application xmlns=   
    "https://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
     StartupUri="Page1.xaml"
     x:Class="Example.SimpleApp">
. . . 
</Application>

This definition first specifies WPF's namespace as the default for this element, then defines a prefix for the XAML namespace. (XAML is used for more than WPF, so these two namespaces aren't synonymous.) It next uses the StartupUri attribute to indicate the name of the XAML page that should be loaded and displayed when the application is started. The final attribute, Class, is used to identity the class that contains the code associated with this Application. As mentioned earlier, WPF applications typically contain both XAML and code written in C# or Visual Basic, and so a code-behind file is used to contain code for this class. Following this opening Application tag appears the rest of the XAML used to define this application, all of which is omitted here, followed by the closing tag for the Application element.

Even though all WPF applications derive from the same root class, there are still plenty of choices that a developer needs to make. A big one is deciding whether an application should provide a traditional dialog-driven interface or a navigational interface. A dialog-driven interface provides the buttons and other elements that every Windows user is familiar with. A navigational interface, by contrast, acts much like a browser. Rather than opening a new window for a dialog, for instance, it commonly loads a new page. Interfaces like this are implemented as a group of pages, each consisting of a user interface defined in XAML together with logic expressed in a programming language. Like HTML-defined browser pages, XAML provides a Hyperlink element that can be used to link pages together. A user navigates through these pages much as she would through the pages of a Web-based application, relying on a History list to move back and forth. Don't be confused, however—this is still a Windows application. While XBAPs will typically use this kind of interface, it's also perfectly legal for a standalone Windows application to interact with its user through a navigational interface. The choice is made by the people who create the application.

Whatever interface style an application uses, it usually displays one or more windows. WPF provides a few choices for doing this. The simple Window class provides basic windowing functions, such as displaying, hiding, and closing a window, and it's typically used by a WPF application that's not using a navigational interface. NavigationWindow, used by applications that do have a navigational interface, extends the basic Window class with support for navigation. This support includes a Navigate method that allows the application to move to a new page, a journal that keeps track of the user's navigation history, and various navigation-related events.

Layout and Controls

To organize the various parts of an interface, a WPF application uses panels for layout. Each panel can contain children, including controls such as buttons and text boxes, and other panels. Different kinds of panels provide different layout options. A DockPanel, for example, allows its child elements to be positioned along the edges of the panel, while a Grid allows positioning its children precisely on a grid, just as its name suggests. The developer defines the number of rows and columns in the grid, then specifies exactly where any children should be placed. A Canvas lets a developer position its children freely anywhere within the panel's boundaries.

Like any user interface technology, WPF provides a large set of controls, and developers are free to create custom controls as well. The standard set includes Button, Label, TextBox, ListBox, Menu, Slider, and other traditional atoms of user interface design. More complex controls are also provided, such as SpellCheck, PasswordBox, controls for working with ink (as with a Tablet PC), and more.

As usual in a graphical interface, events generated by the user, such as mouse movements and key presses, can be caught and handled by the controls in a WPF application. While controls and other user interface elements can be fully specified using XAML, events must be handled in code. For example, here's a XAML definition of a simple Button on a Canvas:

<Canvas xmlns=
   "https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="Example.CodeForCanvas">
  <Button Click="Button_Click">
   Click Here
  </Button>
</Canvas>

The opening Canvas tag starts by defining the usual WPF and XAML namespaces. It then specifies that the code associated with this XAML can be found in a class named CodeForCanvas, which is contained in the .NET Framework namespace Example. Next comes the definition of the Button itself, specifying "Click Here" as its on-screen text. The Click attribute on the opening Button tag indicates that this button relies on a method called Button_Click to handle the click event. The code for that method might look like this:

namespace Example {
  public partial class CodeForCanvas : Canvas  {
    void Button_Click(object sender, RoutedEventArgs e)    {
      Button btn = e.Source as Button;
      btn.Background = Brushes.Purple; 
    }
  }
}

The namespace and class name match that specified in the Canvas tag just shown. The class CodeForCanvas inherits from the base Canvas class provided by WPF, and it's defined as a partial class. Partial classes were a new addition in version 2.0 of the .NET Framework, and they allow combining code defined separately into a single class. In this case, the XAML-defined Canvas generates a partial class that gets combined with the partial class shown here. The result is a complete class capable of both displaying a canvas with a button and handling its event.

The Button_Click method to handle that event is provided within the CodeForCanvas class. It follows the usual .NET Framework conventions for an event, although the event's arguments are conveyed using the WPF-defined RoutedEventArgs class. This class's Source property contains a reference to the Button that generated the event, which the method uses to change the button's color to purple.

As this simple example suggests, the elements in a WPF user interface are organized into a visual tree. Here, the tree consists of just a Canvas with a single child Button, but in a real WPF application, this tree is typically much more complex. To actually create the on-screen interface, this visual tree must be rendered. Whenever possible, WPF relies on hardware rendering, letting the graphics card installed on the application's machine handle the work. If the machine's graphics hardware isn't up to the job, however, WPF will render the interface using its own software. The decision is made at run time by WPF—developers don't need to do anything special.

Whether rendering is done in hardware or software, WPF always relies on an approach known as retained mode graphics. The creators of an application define what the visual tree looks like, typically using a combination of XAML and code. WPF itself then retains the information in this tree. Rather than requiring the application to repaint all or part of a window when the user uncovers it, for example, WPF handles this on its own. The elements that comprise the tree are stored as objects, not as pixels on the screen, and so WPF has enough information to handle this kind of rendering. Even if a window and the controls it contains are resized, WPF can re-render everything on its own. Because it understands the form of the graphics—lines, ellipses, and so on—and because it relies on vector graphics rather than maps of pixels, WPF has enough information to recreate the interface at the new size.

Styles and Templates

It's often useful to be able to define how some user interface element looks once, then apply that look over and over. Cascading Style Sheets (CSS) allow doing this in HTML pages, for example. WPF provides something similar with styles. The ability to define styles can be quite useful, as the popularity of CSS stylesheets suggests. They allow better separation between designers and developers, for instance, allowing a designer to create a uniform look for an interface while letting the developer ignore these details.

Using XAML's Style element, the creator of a WPF application can define one or more aspects of how something should look, then apply that style over and over. For example, a style named ButtonStyle might be defined like this:

<Style x:Key="ButtonStyle">
  <Setter Property="Control.Background" Value="Red"/>
  <Setter Property="Control.FontSize" Value="16"/>
</Style>

Any Button defined using this style would be given a red background and use a font size of 16. For example:

  <Button Style="{StaticResource ButtonStyle}">
   Click Here
  </Button>

As the appearance of "StaticResource" in this example suggests, WPF styles are typically defined as a resource, which is just data defined separately from an application's code.

Styles allow more than the simple example shown here might suggest. A style can be derived from another style, for instance, inheriting and perhaps overriding its settings. A style can also define triggers that specify common aspects of interactive behavior. For example, a style might specify that hovering the mouse over a Button should cause the button's background to turn yellow.

WPF also supports the use of templates. A template is similar to a style, and two different kinds are available:

  • Data templates: allow using XAML's DataTemplate element to specify a group of characteristics for how data should be displayed. Colors, alignment, and more can be defined once in a data template, then used elsewhere in an application's user interface.
  • Control templates: allow using XAML's ControlTemplate element to define the appearance of a control.

Providing a straightforward way for an application's creators to define the appearance of its interface makes sense. In WPF, styles and templates are primary mechanisms for doing this.

Text

Most user interfaces display at least some text, and some display little else. Yet for most people, reading text on a screen can't compare with reading a printed page. We've become accustomed to the high-quality depictions of letters and the relationships between them typically found in books and magazines. When we read on-screen text, things just aren't the same—the text somehow doesn't feel as readable.

WPF aims at closing this gap, making on-screen text as readable as a printed page. Toward this end, WPF supports industry-standard OpenType fonts, allowing existing font libraries to be used. It also supports the more recently defined ClearType technology. Through sub-pixel positioning, a technique for individually lighting up the sub-elements that make up each pixel on modern display screens, ClearType allows text to look smoother to the human eye. WPF also provides low-level support for rendering text via the Glyphs class. As described later, this class is used by XPS documents to represent characters.

To further improve readability, WPF also allows extras such as ligatures, where a group of characters are replaced by a single connected image. For instance, the group "ffi" will typically be replaced in a printed page by a single connected ligature containing those three characters. Adding this to on-screen text makes the reader feel more at home, even if she doesn't consciously perceive the details that create that feeling.

Documents

Making text more readable is a good thing, since text appears in buttons and lists and many other places in a user interface. Yet we care most about text when we're reading longer chunks of it, such as in a document. Accordingly, improving on-screen readability also requires improving how documents are displayed. Toward this end, WPF supports two kinds of documents: fixed documents and flow documents.

Fixed documents look exactly the same whether they're rendered on a screen or a printer. Knowing that a document will always look the same is important for some forms, legal documents, and other kinds of publications, and so fixed-format documents are important in a number of areas. The fixed-format documents supported by WPF are defined by XPS, which is described later in this paper. A fixed document's contents can be specified using XAML's FixedDocument element. This simple element contains just a list of PageContent elements, each containing the name of a page in the fixed document. To display a fixed document, WPF provides the DocumentViewer control. This control provides read-only display of an XPS document, letting the reader move backward and forward in the document, search for specific text, and more.

While fixed documents are meant to be used both on a screen and on paper, flow documents are intended solely for on-screen display. To make its contents as readable as possible, a flow document can adjust how a document's text and graphics are displayed based on the window size and other factors. Unsurprisingly, flow documents are defined using a XAML element called FlowDocument. Here's a simple example:

  <FlowDocument 
    ColumnWidth="300" 
    IsColumnWidthFlexible="True" 
    IsHyphenationEnabled="True">
      <Paragraph FontSize="12">
       <Bold>Describing WPF</Bold>
      </Paragraph>
      <Paragraph FontSize="10">
       WPF is the user interface technology for the .NET 
       Framework 3.0. It provides a unified foundation for modern 
       user interfaces, including support for documents, two- and 
       three-dimensional graphics, media, and more. It also 
       allows using the same approach (and the same code) for 
       creating standalone Windows applications and applications 
       that run inside a browser.
      </Paragraph>
  </FlowDocument>

This document asks to be displayed in a column with a width no less than 300. (The width is measured in device-independent pixels, each of which is defined to be 1/96th of an inch.) In the very next line, however, the document's creator says that this width is flexible by setting the IsColumnWidthFlexible property to true. This authorizes WPF to change the width and number of columns that will be used to display this document. If the user changes the width of the window in which this document is displayed, for example, WPF can increase or decrease the number and the width of columns used to display the document's text.

Next, the document requests hyphenation by setting the IsHyphenationEnabled property to true. Following this are the two paragraphs this document contains. The text inside each one is contained within a Paragraph element, each setting a different font size. The text in the first paragraph also indicates that it should be displayed in bold.

WPF defines several more FlowDocument options for improved readability. For instance, if the IsOptimalParagraphEnabled property is set to true, WPF will distribute white space as evenly as possible throughout a paragraph. This can prevent the "rivers" of white space that hurt readability, something that's commonly done with printed documents. Flow documents also allow annotations, such as adding notes in ordinary text or, on Tablet PCs, in ink. Each annotation consists of an anchor that identifies what content in the document an annotation is associated with and cargo that contains the content of the annotation itself.

To display a FlowDocument, WPF includes a few different controls. They are the following:

  • FlowDocumentPageViewer: allows moving through a document one page at a time. This control provides a forward and back button along with a zoom control that allows the user to resize the document she's reading.
  • FlowDocumentScrollViewer: provides a more traditional scrolling view of a FlowDocument, complete with a scrollbar on the right side of the page.
  • FlowDocumentReader: combines the functionality of both FlowDocumentPageViewer and FlowDocumentScrollViewer. This control allows the user to switch between a page-oriented view of a flow document (including seeing two pages at a time) and a scrolling view.

As more and more information is delivered digitally, the quality of the on-screen reading experience becomes more important. By providing adaptive display of information through flow documents, WPF attempts to improve this experience for Windows users.

Images

Whether they represent company logos, pictures of sunsets, or something else, images are a fundamental part of many user interfaces. In WPF, images are typically displayed using the Image control. To show a JPEG file, for example, the following XAML could be used:

<Image 
 Width="200" 
 Source="C:\Documents and Settings\All Users\Documents\
  My Pictures\Ava.jpg" />

The image's width is set to 200, and once again, the units here are device-independent pixels. The file that contains the image is identified using the Source attribute.

An image file can contain information about the image—metadata—such as keywords and ratings applied by users, and WPF applications can read and write this information. An image can also be used in more interesting ways, such as painting it onto one face of a revolving three-dimensional object. Although the simple example shown here illustrates a common case, WPF allows images to be used in a significantly broader way.

The WPF Image control can display images stored in various formats, including JPEG, BMP, TIFF, GIF, and PNG. It can also display images stored using Microsoft's Windows Media Photo (WMPhoto) format, new with Windows Vista. Whatever format is used, WPF relies on the Windows Imaging Component (WIC) to produce the image. Along with coder/decoders (commonly known as codecs) for all the image formats just listed, WIC also provides a framework for adding third-party codecs.

Video and Audio

As both network and processor speeds have increased, video has become a larger part of how people interact with software. People also spend a good deal of time listening to music and other audio on their computers. Accordingly, WPF provides built-in support for both.

That support depends on the MediaElement control. Here's a simple XAML example of how this control might be used:

<MediaElement 
 Source="C:\Documents and Settings\All Users\Documents\
  My Videos\Ruby.wmv" /> 

This control can play WMV, MPEG, and AVI video, along with various audio formats.

Two-Dimensional Graphics

For the last twenty years, creators of two-dimensional graphics in Windows have relied on the Graphics Device Interface (GDI) and its successor, GDI+. Yet even Windows Forms applications must access this functionality through a distinctly different namespace—2D graphics aren't integrated into the user interface technology itself. The situation was even worse for three-dimensional graphics, since an entirely separate technology, Direct3D, was required. With WPF, this complexity goes away for a large share of applications. Both 2D and 3D graphics can be created directly in XAML or in procedural code using the WPF libraries. Like everything else in WPF, the elements they use are just another part of an application's visual tree.

For 2D graphics, WPF defines a group of shapes that applications can use to create images. They are:

  • Line: draws a straight line between two points.
  • Elllipse: draws an ellipse.
  • Rectangle: draws a rectangle.
  • Polygon: draws a closed shape defined by a group of connected straight lines.
  • Polyline: draws an open shape defined by a group of connected straight lines.
  • Path: draws shapes described by an arbitrary path. The shapes can be open or closed, and the lines in the path can be straight or curved. In fact, all of the other shapes exist solely for convenience, since Path can be used to draw lines, ellipses, rectangles, polygons, polylines, and more.

Using these classes to create simple graphics is straightforward. For example, the following XAML draws a red ellipse:

<Ellipse Width="30" Height="10" Fill="Red" />

Filling a shape relies on a brush. The example above uses the default, which is a solid color brush, but WPF provides several other options. For example, a rectangle filled with a color gradient changing horizontally from red to yellow can be defined with:

<Rectangle Width="30" Height="10" 
 Fill="HorizontalGradient Red Yellow" />

Several other brushes are also available, including a vertical gradient, a radial gradiant, and brushes that paint with images, bitmaps, and more. Although it's not shown here, shapes can also use pens to specify the color, width, and style of their outline.

A key thing to understand about WPF is that because everything is built on a common foundation, combining different aspects is straightforward. An application can display an Image inside a Rectangle, place an Ellipse within a Button, and much more. Because of this, combining 2D graphics with 3D graphics and other parts of an interface is straightforward.

Along with shapes, WPF also provides another group of classes for working with two-dimensional graphics. Known as geometries, these classes are similar in many ways to shapes. Like shapes, which include choices such as Line, Rectangle, Ellipse, and Path, geometries provide options such as LineGeometry, RectangleGeometry, EllipseGeometry, and PathGeometry. The most important difference between the two kinds of classes is that while shapes are typically used to draw visible images, geometries are more often used to define regions. If a square image needs to be cropped to fit inside a circle, for example, the EllipseGeometry class can be used to specify the circle's boundaries. Similarly, if an application wishes to define a hit-testing region, such as an area in which mouse clicks will be detected, it can do this by specifying a geometry for that region.

Finally, it's worth mentioning that everything described in this section is actually implemented on top of a lower-level interface called the visual layer. It's possible to create graphics, images, and text using this layer directly. While doing this can be useful in some situations, such as for creating simple, high-performance graphics, the great majority of applications will use shapes and the other higher-level abstractions that WPF provides.

Three-Dimensional Graphics

Two-dimensional graphics are a common part of Windows interfaces, and so WPF provides quite a bit of technology in this area. Three-dimensional graphics are less commonly used today, however, even though they can provide substantial value through better data visualization, 3D charts, product renderings, and more. Working in 3D has traditionally required a distinct skill set, one that's not commonly found outside of game developers and other specialized groups. By making support for 3D graphics part of the standard environment, WPF aims at changing this.

Without WPF, 3D development on Windows typically relies on the Direct3D API. Like everything else in WPF, its support for 3D graphics uses Direct3D under the covers, but developers are presented with a significantly simpler world. While there are still cases where it makes sense to use Direct3D rather than WPF, as described later in this paper, Microsoft's intent is that mainstream 3D development for Windows interfaces use WPF.

To display 3D graphics in WPF, an application uses the Viewport3D control. This control essentially provides a window into the three-dimensional world the application describes. A Viewport3D control can be used anywhere in a WPF interface, allowing 3D graphics to appear wherever they're needed.

To create a 3D scene, a developer describes one or more models, then specifies how those models should be lit and viewed. As usual, all of these things can be specified using XAML, code, or a mix of the two. To describe a model, WPF provides a GeometryModel3D class that allows defining the model's shape. Once a model is defined, its appearance can be controlled by applying different kinds of material. The SpecularMaterial class, for instance, makes a surface look shiny, while the DiffuseMaterial class does not.

Regardless of the materials it uses, a model can be lit in various ways. DirectionalLight provides light that comes from a specific direction, while AmbientLight provides uniform lighting for everything in a scene. Finally, to define how the model should be viewed, the developer specifies a camera. A PerspectiveCamera, for instance, allows specifying the distance and perspective from which a model is viewed, while an OrthographicCamera does the same thing, except without perspective: objects further from the camera don't appear smaller.

Creating complex 3D scenes directly in either XAML or code isn't simple. It's safe to assume that for the great majority of WPF applications that use 3D, developers will rely on graphical tools to generate the necessary definitions. However it's accomplished, the ability to use 3D graphics in a standard user interface has the potential to improve significantly the quality of what users see on their screens.

Transformation and Effects

Along with providing a way to define shapes and other elements, WPF also offers developers the ability to transform these elements by rotating them, changing their size, and more. In XAML, elements such as RotateTransform and ScaleTransform are used to do this. These transformations can be applied to any user interface element. Here's a simple example:

</Button>
  <Button Content="Click Here">
   <Button.RenderTransform>
    <RotateTransform Angle="45" />
   </Button.RenderTransform>
  </Button>

The RotateTransform element rotates the button by 45 degrees. While rotating a button like this isn't especially useful, the fact that it's possible indicates the generality of WPF's design. Because the various aspects of a user interface don't rely on different underlying technologies, they can be combined in diverse ways.

WPF also includes a few pre-defined effects. Like transformations, these effects can be applied to various aspects of a user interface, such as Buttons, ComboBoxes, and others. They include a blur effect that makes the interface element appear fuzzy, an outer glow effect that makes an element appear to glow, and a drop shadow effect that adds a shadow behind an interface element.

Animation

The ability to make the elements in an interface move—to animate them—can be very useful. Clicking on a button might cause the button to appear to move down, then up, for instance, giving better feedback to the user. More complex animations can help create interfaces that engage their users by directing their attention and telling stories. WPF's animation support makes this possible.

As with transformations, animations can be applied to many different aspects of the interface, including buttons, shapes, images, and more. Animation is accomplished by changing the value of one or more of an object's properties over time. For example, an Ellipse might appear to be slowly squashed by incrementally decreasing its Height property over a period of two seconds.

It's often useful to define a group of related animations. To allow this, WPF provides the Storyboard class. Each Storyboard can contain one or more timelines, and each of these can contain one or more animations. Various kinds of timelines are provided, allowing animations to run sequentially or in parallel. Here's a simple (although slightly incomplete) XAML example that illustrates squashing an Ellipse:

    <Ellipse Width="100" Height="50" Fill="Blue"
     Name="EllipseForSquashing">
     . . . 
     <Storyboard>
      <DoubleAnimation
       Storyboard.TargetName="EllipseForSquashing" 
       Storyboard.TargetProperty="Height"
        From="50" To="25" Duration="0:0:2" />
       </Storyboard>
       . . . 
    </Ellipse>      

The example begins with the definition of an Ellipse, as seen earlier in this paper. Here, however, the Name property is also used, assigning an identifier that allows this Ellipse to be referenced later. Some details are omitted, but to define the animation in XAML, a Storyboard element must appear. Because Ellipse's Height property is of the type double, the Storyboard contains a DoubleAnimation element. This element specifies the name of the Ellipse being animated, the property that will be changed, and exactly what those changes should be. Here, the value of Height is being changed from 50 to 25 over a period of two seconds.

Animations can be much more complex than this. They can be triggered by events, such as mouse clicks, be paused and then resumed, be set to repeat some number of times (or forever), and more. The goal is to allow developers to create user interfaces that provide better feedback, offer more functionality, and are all-around easier to use than they otherwise might be.

Data Binding

Most user interfaces display some kind of data. To make life simpler for the developers who create those interfaces, data binding can be used to make displaying data easier. Data binding allows directly connecting what a WPF control displays with data that lives outside that control. For example, the value of the Text property in a WPF TextBox control might be bound to a property called Name in an Employee object that's part of this application's business logic. A change to either property could then be reflected in the other. If a user updated the value in the TextBox, the Employee object's Name property would also change, and vice-versa.

Creating this kind of connection between properties in two objects requires using the WPF Binding class. Here's a slightly simplified XAML illustration of how this might look:

<TextBox . . . >
 <TextBox.Text>
  <Binding Path="Name" />
 </TextBox.Text>
</TextBox>

In this example, the Binding element's Path attribute is used to identify the property to which the TextBox's Text property should be bound. Path is used when the object this property is part of (which will be specified at runtime) is a Common Language Runtime (CLR) object, defined in a language such as C# or Visual Basic. Along with CLR objects, WPF's data binding can also connect to XML data directly using Binding's XPath property. This option creates an XPath query that selects one or more nodes in an XML document referencing the specified data.

More complex data binding options are also possible. For example, list bindings allow the contents of a ListBox control to be populated from any CLR object that implements the standard IEnumerable interface. If necessary, data can also be filtered or sorted before it's displayed. (While it is possible to bind to an ADO.NET Dataset, however, WPF has no direct support for binding to data in a relational database management system.) Whatever data binding option is used, the intent is to make a common requirement—displaying data in a user interface—as straightforward as possible.

User Interface Automation

The most common user of a WPF interface is, of course, a person. But there are times when a user interface needs to be driven not by a human being, but instead by other software. WPF's user interface (UI) automation makes this possible.

Suppose, for example, that a developer wishes to create automated test scripts for an interface. Using the programmatic access that UI automation provides, she can create scripts that drive the interface just as a human user would. UI automation is also useful for creating accessibility aids, such as a tool that reads aloud the various elements of the interface. Because it allows programmatically walking through the tree that contains those elements, UI automation makes building these kinds of tools possible.

To allow this, WPF creates a UI automation tree. This tree consists of AutomationElement objects, each representing something in the interface. The root of the tree is the Desktop, and each open application is a child of this root. The tree continues into each of these applications, with each WPF control represented as one (or sometimes more than one) AutomationElement objects. To allow complete programmatic access to the interface, everything that a user can interact with is represented as a distinct AutomationElement. For example, a control with multiple buttons will have both the control itself and each button represented as a distinct AutomationElement object. Building this level of granularity into the UI Automation tree allows a client application, whether it's a test script, an accessibility aid, or something else, to access each component of the interface just as would a human user.

UI automation isn't the most mainstream aspect of WPF. Most people will probably never use it. Yet those who need it, such as software testers and users with disabilities, really need it. Something doesn't have to be widely used to be important.

Applying Windows Presentation Foundation

WPF contains a remarkable amount of technology. While all of it relates to interacting with people, the technology is applied today in three related ways: standalone WPF applications, XBAPs, and XPS documents. This section looks at each of these three.

Standalone WPF Applications

The most general way to use WPF is in a standalone application. Standalone WPF applications run like any other Windows application—they don't require a Web browser. Accordingly, standalone applications can have full trust, so all of WPF's capabilities can be used. Full trust also means that standalone WPF applications can freely use other services available on the machine, such as Windows Communication Foundation (WCF).

Like other Windows applications, a standalone WPF application can be installed from a local disk or from a network server. It can also be installed using ClickOnce, a facility in the .NET Framework. ClickOnce provides a straightforward way for Internet Explorer users to download and install Windows applications, including WPF applications, and to have those applications automatically updated when they change.

XAML Browser Applications: XBAPs

While standalone WPF applications offer the most capability, they're not always the right choice. Plenty of situations make more sense with a client that runs in a Web browser rather than as a Windows application. To allow these clients to present modern user interfaces, WPF provides XBAPs.

As the figure below shows, an XBAP runs inside Internet Explorer. XBAPs can act as a client for Web applications built using ASP.NET, JavaServer Pages (JSP), or other Web technologies. To communicate back to this Web application, the XBAP can use HTTP or SOAP. Whatever server platform is used, an XBAP is always loaded via ClickOnce. It presents no dialogs or prompts to the user during this process, however; an XBAP loads just like a Web page. Because of this, XBAPs don't appear on the Start menu or in Add/Remove Programs.

Aa663364.introducingwpf7b(en-us,MSDN.10).gif

Figure 7. An XBAP running inside Internet Explorer

While it's not strictly required, XBAPs typically present a navigational interface to the user. This lets the application behave like a Web client, which is probably what the user expects. In Internet Explorer 7, an XBAP uses the forward and back buttons of the browser itself, and the XAML pages a user accesses will appear in the browser's history list. In Internet Explorer 6, the XBAP displays its own forward and back buttons, along with maintaining its own history list. The XBAP can determine which environment it's running in and do the right thing; the developer need not create different versions for each browser.

Because it's loaded from the Web and runs inside a browser, an XBAP is given only limited trust by the .NET Framework's code access security. Because of this, there are a number of things that a standalone WPF application can do that an XBAP cannot. For example, an XBAP deployed from the Internet zone can't do any of the following:

  • Create standalone windows.
  • Display application-defined dialogs.
  • Display a Save dialog launched by the XBAP itself.
  • Access the file system beyond a limited Isolated Storage area.
  • Act as a UI automation client.
  • Use WCF. WCF applications must have full trust, and so XBAPs deployed from the Internet can't use it. They can instead use ASP.NET Web services, commonly known as ASMX, to communicate with the Web application from which they were loaded.
  • Use any user interface code created with Windows Forms, Microsoft Foundation Classes (MFC), or direct Win32 calls. Although standalone WPF applications can interoperate with all of these older technologies, as described later, none of them are allowed in an XBAP's limited trust environment.
  • Use unmanaged code.

As mentioned earlier, it's possible to use the same code base for both a standalone WPF application and an XBAP. To allow this, a developer might use conditional compilation, wrapping any functionality that's not allowed in an XBAP inside ifdefs. The XBAP version can do most of what the standalone application can do, including displaying documents, using two-dimensional and three-dimensional graphics, playing video and audio, and more. It can also take advantage of whatever graphics hardware is available in the machine it's running on.

Along with XBAPs, it's also possible to display pure XAML pages directly in Internet Explorer. Referred to as loose XAML, this can be useful for showing static pages in the browser. Handling events requires code, however, which means creating an XBAP.

XBAPs allow developers to use most of WPF's capabilities in a browser application. They also allow a common programming model, using mostly the same code, for standalone applications and browser applications. For Web applications whose clients target newer Windows platforms, XBAPs are likely to be an attractive choice.

XPS Documents

Fixed-format documents, which in the WPF world means XPS documents, clearly have a role in user interfaces. As described earlier, WPF provides the DocumentViewer control for displaying XPS documents. Yet while it certainly makes sense to include this control in WPF, it's less obvious why XPS itself should be considered part of WPF. After all, the XPS specification provides a highly detailed way to define fixed-format documents, and the documents themselves can be used in different ways. Everything else in WPF is focused solely on creating a user interface. Given its broader purview, why include XPS under the WPF umbrella?

One big reason is that XPS documents are defined using XAML. Only a small subset of XAML is used, including the Canvas element for layout, the Glyphs element for representing text, and the Path element for creating two-dimensional graphics, but every XPS document is really a XAML document. Given this, viewing XPS as part of WPF is plausible.

Still, one of XPS's most important applications isn't about on-screen user interfaces. Beginning with Windows Vista, XPS becomes a native print format for Windows. XPS acts as a page description language, and so XPS documents can be rendered directly by XPS-aware printers. This allows using a single description format—XAML—all the way from the screen to the printer. It also improves on existing GDI-based print mechanism in Windows, providing better print support for complex graphic effects such as transparency and gradients.

Along with XAML, an XPS document can contain binary data such as images in various formats (including JPEG, PNG, TIFF, and WMPhoto), font data, information about document structure, and more. If necessary, XPS documents can also be digitally signed using the W3C XML Signature definitions and X.509 certificates. Whatever it contains, every XPS document is stored in a format defined by the Open Packaging Conventions (OPC). OPC specifies how the various parts of an XML document (not just an XPS or XAML document) are related, how they're stored in a standard ZIP format, and more. Microsoft Office 2007 also uses OPC for its XML formats, providing some commonality between the two kinds of documents.

Users of a WPF application can view XPS documents via the WPF DocumentViewer control, as mentioned earlier. Microsoft also provides an XPS viewer application, built on the DocumentViewer control, as shown below. Like the control, this application lets users move through documents page by page, search for text, and more. XPS documents are not Windows-specific, and so Microsoft plans to provide XPS viewers for other platforms as well, such as the Apple Macintosh.

Aa663364.introducingwpf7(en-us,MSDN.10).gif

Figure 8. An XPS viewer allows reading an XPS document a page at a time.

To let developers work with XPS documents, WPF provides a set of APIs to create, load, and manipulate them. WPF applications can also work with documents at the OPC level, allowing generalized access to XPS documents, Office 2007 documents, and others. Applications built using Microsoft's Windows Workflow Foundation can also use these APIs to create workflows that use XPS documents.

By allowing applications to display and work with fixed format documents, WPF integrates this component of modern user interfaces into its consistent approach. By using this same format to print documents, Windows Vista allows a better match between what people see on the screen and what they see on paper. While this type of document probably isn't the first thing people expect from a user interface technology, the broad use of XPS illustrates the range that a technology like WPF can cover.

Tools for Windows Presentation Foundation

WPF provides lots of functionality for developers, which is a good thing. No matter how powerful it is, though, a technology can be made much more useful by good tools. For WPF, Microsoft provides one tool aimed specifically at developers and another aimed at designers. This section takes a brief look at both.

For Developers: Visual Studio

Visual Studio is Microsoft's flagship tool for software developers. When WPF is initially released, Microsoft will provide extensions for Visual Studio 2005 that let developers create WPF applications. The next Visual Studio release, code-named "Orcas", will add more, including a Visual Designer for WPF (which has a code name of its own: "Cider"). Using this visual tool, developers will be able to create WPF interfaces graphically, then have the underlying XAML generated automatically. Although no official release date has been announced, Orcas is scheduled to ship sometime in 2007.

For Designers: Expression Interactive Designer

As described earlier, a primary goal of WPF is to make designers first-class citizens in the creation of user interfaces. XAML makes this possible, but only if tools are provided that let designers work in this new world. Toward this end, Microsoft has created Expression Interactive Designer.

As the screen shot below suggests, Expression Interactive Designer provides some aspects of traditional design tools, allowing its user to work in familiar ways. Yet the Designer is exclusively focused on creating interfaces for WPF applications. (In fact, this tool's interface is itself built using WPF.) Notice, for example, the list of WPF controls on the upper right of the screen below, and the graphical timeline at the bottom. All of these correspond to WPF capabilities described earlier in this paper, and all are made available for an interface designer to use. Animations can be created graphically, as can transformations, effects, and more. The result of the designer's work is expressed in a XAML file generated by the tool, which can then be imported into Visual Studio.

Aa663364.introducingwpf8(en-us,MSDN.10).gif

Figure 9. Expression Interactive Designer lets designers create WPF interfaces.[fig 8]

Expression Interactive Designer is one of three members of Microsoft's Expression family. The others are Expression Web Designer, a tool for creating standards-based Web interfaces, and Expression Graphic Designer, a tool for creating vector and/or bitmap images. Of the three, only Expression Interactive Designer is focused exclusively on creating user interfaces for WPF applications. A designer might well use the others to create parts of a user interface—maybe the interface's GIF images are created with Expression Graphic Designer, for instance—but these tools aren't specific to WPF. And although dates haven't been announced, all of the Expression tools are scheduled to ship sometime after the release of WPF.

Windows Presentation Foundation and Other Microsoft Technologies

Like most new Microsoft technologies, WPF affects other parts of the Windows world. Before looking at these effects, though, it's important to understand that installing WPF on a system doesn't break any software that uses Windows Forms, MFC, or any other existing technology. While new applications written for systems that support the .NET Framework 3.0 will most likely build their interfaces using WPF, applications that use these older technologies will continue to run unchanged.

Windows Presentation Foundation and Windows Forms

Since the initial release of the .NET Framework, many applications have been created using Windows Forms. Even with the arrival of WPF, some applications will continue to use Windows Forms. For example, anything that must run on systems where WPF isn't available, such as older versions of Windows, will most likely choose Windows Forms for its user interface. New applications might also choose Windows Forms over WPF for other reasons, such as the broad set of controls available for Windows Forms.

Even applications built using WPF might benefit from using some aspects of Windows Forms. For example, Windows Forms today has a larger set of controls available than does WPF. The DataGridView control introduced with version 2.0 of the .NET Framework has no analog in WPF, and third parties have created Windows Forms controls for many other uses. Letting WPF applications use these existing controls can make sense in some cases. Conversely, WPF offers many things that Windows Forms does not, such as 3D graphics and animations. Allowing an existing Windows Forms application to incorporate parts of WPF's functionality also makes sense.

Both of these things are possible. A WPF application can host Windows Forms controls, and a Windows Forms application can host WPF controls. A user can interact with WPF dialogs and Windows Forms dialogs in the same application, typically without being aware that there's any difference.

To host Windows Forms controls, a WPF application relies on WPF's WindowsFormsHost control. As its name suggests, this control is capable of hosting Windows Forms controls, allowing them to be used within the WPF application. It can also host ActiveX controls, giving WPF applications access to the large existing library created using this older technology. Similarly, a Windows Forms application uses ElementHost, a Windows Forms control that's capable of hosting WPF controls, panels, and other elements. The tools for each technology can also work with software written for the other. WPF's Visual Designer can be used to position Windows Forms controls, while the Windows Forms designer can be used to position WPF controls.

Using WPF and Windows Forms together does have some restrictions. Layering a WPF control on top of a Windows Forms control won't work, for example; the Windows Forms control will always be on top. WPF's transparency effects also won't work well with Windows Forms controls, nor will WPF transformations. And because the WindowsFormsHost and ElementHost controls require full trust, a WPF application that uses them can't run as an XBAP. Still, a large percentage of Windows applications can use both WPF and Windows Forms to create their user interface.

Windows Presentation Foundation and Win32/MFC

Before the release of the .NET Framework in 2002, Windows developers commonly built user interfaces using either direct calls to Win32 APIs or MFC, which provided C++ wrappers around those APIs. Accordingly, plenty of code exists today with interfaces created in this style. What happens to this code in a WPF world?

The answer is similar to the situation with Windows Forms. Once again, WPF controls can be hosted within existing Win32/MFC code, and existing Win32/MFC controls can be hosted within WPF. (In fact, the facilities for interoperation between WPF and Windows Forms are actually built on top of the Win32/MFC interoperability services.) WPF provides the HwndHost class to allow using Win32/MFC controls in WPF, and the HwndSource class to let WPF controls be used in a Win32/MFC application. Each class maps between the two technologies as required. HwndHost, for instance, makes the hWnd used to reference a Win32/MFC control look like a WPF control. HwndSource does the opposite, making a WPF control look like an hWnd.

As with Windows Forms, there are some limitations in mixing these two worlds. In fact, since the Windows Forms interoperability relies on HwndHost and HwndSource, all of the restrictions described earlier for Windows Forms controls, such as limitations on layering and transparency, apply here, too. Also, unlike Windows Forms, applications that mix WPF with Win32/MFC code face the added challenge of interoperating between the WPF managed code environment and the unmanaged world of Win32. For this and other reasons, WPF applications that use Win32/MFC code can't run as XBAPs. As before, however, the key point is that Windows application can use WPF and Win32/MFC together. Using WPF doesn't require throwing away all of an application's existing user interface code.

Windows Presentation Foundation and Direct3D

Direct3D, part of Microsoft's DirectX family of APIs, is a mainstay for Windows developers who create three-dimensional graphics. The advent of WPF in no way obsoletes Direct3D. In fact, as described earlier, WPF relies entirely on Direct3D for rendering. Yet since WPF also allows developers to create 3D graphics, developers working in 3D must decide between the two.

The decision isn't especially difficult, however. Direct3D is still the best choice for intensive 3D development, such as games and 3D-centered technical applications, e.g., high-end scientific visualization. At least in its first release, WPF isn't designed to be a platform for these types of software.

WPF does make 3D graphics available to a much wider and less specialized audience, however. It also allows using 3D graphics on the Web in an XBAP, integrating them naturally with two-dimensional graphics, documents, and other aspects of an application's user interface, and more. It's also possible for a WPF application to host Direct3D code via the HwndHost class described earlier. Both WPF and Direct3D have distinct roles, and both have a good future as part of the Windows platform.

Windows Presentation Foundation and AJAX/"Atlas"

Using AJAX, developers can create browser clients that are more responsive to users. AJAX allows the user to interact with an application without requiring a page refresh (and thus a round trip to the Web server) for each request. To accomplish this, AJAX relies on a browser's support for the XMLHttpRequest object, an idea that first appeared in Internet Explorer 5.0 in the late 1990s. By the middle of the next decade, support for XMLHttpRequest had become widespread in browsers, and the AJAX phenomenon was born.

Creating AJAX clients isn't especially simple, however. To help in the process, Microsoft has created a set of technologies code-named "Atlas." Atlas is a set of libraries, controls, and more for creating AJAX applications. It consists of a client script library that can work in various browsers—not just Internet Explorer—and server-side extensions to ASP.NET. The goal is to make building Web applications with AJAX clients simpler.

The widespread browser support for AJAX makes it very attractive to developers. Yet even though AJAX allows creating much more interactive interfaces for Web users, it doesn't add support for a wider range of content types. Graphics, video, animations, and other more modern styles of interaction aren't supported by AJAX alone. For clients that support WPF, applications that need these will likely be written instead as XBAPs.

Windows Presentation Foundation and "WPF/E"

Using XBAPs, a Web application can provide its users with a large fraction of WPF's capabilities. Yet XBAPs require WPF to be installed on the client machine, limiting their applicability. What about Web applications that need to present modern interfaces, but must also be accessible from Macintoshes and other systems that don't support WPF?

A forthcoming technology, code-named "WPF/E, is intended to address this problem. WPF/E—the "E" stands for "Everywhere"—will provide a subset of WPF capabilities on a range of client platforms, including the Macintosh, smaller devices, and others, and on diverse Web browsers, including Internet Explorer, Firefox, and Netscape. This subset includes two-dimensional graphics, images, video, animation, and text. Some of what an XBAP can do is omitted from WPF/E, however, including support for three-dimensional graphics, documents, and hardware acceleration.

To create a WPF/E application, a developer can use JavaScript. WPF/E will also include a cross-platform subset of the .NET Framework, allowing development in C# and Visual Basic. WPF/E is not part of the .NET Framework 3.0, and so it's not scheduled to be released until sometime in 2007. Once it's available, creators of Web applications will have another option, one that provides a range of functions on a range of platforms, for building clients.

Conclusion

User interfaces are a fundamentally important part of most applications. Making those interfaces as effective has possible can have measurable benefits to the people and organizations that rely on them. The primary goal of WPF is to help developers provide these benefits, and so for anybody who creates or uses Windows applications, WPF is big news.

By providing a unified platform for modern user interfaces, helping make designers active participants in creating those interfaces, and allowing a common programming model for standalone and browser applications, WPF aims at significantly improving the Windows user experience. Some of the technologies it supplants had a twenty-year run as the foundation for Windows user interfaces. The intent of WPF is to lay the foundation for the next twenty years.

 

About the Author

David Chappell is Principal of Chappell & Associates (www.davidchappell.com) in San Francisco, California. Through his speaking, writing, and consulting, he helps technology professionals around the world understand, use, and make better decisions about enterprise software.