Introduction to Windows Presentation Foundation

This topic contains the following sections.

WPF Core Types and Infrastructure

Windows Presentation Foundation (WPF) is built on a core set of types and infrastructure that are important for you to understand because they permeate all of WPF. A high percentage of classes in WPF inherit from the following four "building block" classes:





These four classes are typically referred to as the base element classes because they form the basis of a common model for composing user interface (UI). For more information, see Base Elements Overview.

In WPF, a UI is composed of elements that are assembled in a tree hierarchy, which is known as an element tree. The element tree provides a logical and intuitive way for you to create user interfaces (UIs). It is also a structure over which you can layer more powerful UI services. For more information, see Element Tree.

One UI service is the dependency property system, which enables one element to implement a property whose value is automatically shared with its child elements in the element tree. For example, this property system enables the background color of a window to be automatically applied to all child elements of windows that do not specify their own background color. For more information, see Dependency Properties Overview.

Another service that takes advantage of the elementt tree is the routed event system. The Microsoft .NET Framework version 3.0 provides direct events, which are only raised on one element. Routed events, however, can traverse the element tree in a route between the root element and the originator of the event; they can be handled by any element along the route. One type of routed event bubbles up the tree from the originator, which gives all parent elements the option of handling the event. Another type of routed event tunnels down to the originator to provide an opportunity for all parent elements of the originator to preview the event. For more information, see Routed Events Overview.

The main reason to handle events is to capture and process user input. The WPF input system incorporates direct and routed events for this purpose. It also adds more support for text input, focus management, and mouse positioning. For more information, see Input Overview.

Just as the input system operates directly over input devices, the commanding system provides a layer of abstraction that separates input actions from the code that responds to those actions. The commanding system is modeled on the familiar command design pattern. For more information, see Commanding Overview.

Extensible Application Markup Language

WPF constructs UIs by using Extensible Application Markup Language (XAML), which is an XML-based markup language for composing WPF elements and taking advantage of the fundamental WPF services. For example, the following XAML markup composes a UI that consists of a window that has a single button.

  <Button>Hello, XAML!</Button>

WPF takes this UI definition and translates the XAML elements that it comprises into instances of the WPF classes that are required to implement the UI that is defined in XAML, which is shown in the following figure.

Defining a UI by using XAML provides several advantages over traditional presentation technologies:

  • XAML is often more expressive than code for defining UIs and therefore, it typically simplifies UI design.

  • By separating the UI definition from the application logic, WPF helps make your code more maintainable, reusable, and robust when UI changes occur.

  • By separating the UI definition, WPF also allows for multiple design and development tools to operate over a single piece of XAML markup. This enables a workflow that starts with a graphic designer creating a UI and ends with a developer coding application logic to support the UI.

For more information, see XAML Overview


To help you compose your UI, WPF provides a comprehensive set of controls. If these controls do not provide the behavior that your applications require, you can easily build your own custom controls.

Standard Controls

The standard controls that are implemented by WPF derive from the Control base class, either directly or indirectly, and include the following:

Action: Button, ContextMenu, Menu, Separator, StatusBar, Thumb, ToolBar.

WPF also extends support for editing controls with features that include Drag and Drop Overview, the clipboard, text selection, and text manipulation.

For more information and introductory samples, see Control Library Samples

Custom Controls

Even though WPF provides these standard controls, particular applications often require customized controls. When you use styles and templates , you can often change the appearance of an existing control without creating a new control. However, if you need a control that has significantly different behavior from the standard set of controls, you can create your own by deriving from an appropriate base class. For example, the ColorPicker Custom Control Sample creates a custom control that derives from Control (like the standard WPF controls) in order to implement a reusable color picker control. The following illustration shows a custom control.

For more information, see Control Authoring Overview. For introductory samples, see Control Customization Samples.

Data Binding

WPF applications can operate over many types of data, including simple objects, collection objects, WPF elements, XML data, ADO.NET objects, and objects returned from Web services. To facilitate data visualization and interaction, WPF implements a mechanism that allows you to declaratively bind these types of data sources to your application UI.

A data binding is a formal relationship between a binding source (the data source) and a binding target (the data consumer) that ensures synchronization between the two. The following illustration shows this relationship.

Basic data binding diagram

A data binding is encapsulated by the Binding class, which is used in the following example to declaratively establish a binding between a class that implements the PersonName property of the Person object and the Text property of a TextBlock.

<Window ... xmlns:src="clr-namespace:ApplicationNameSpace">
  <!-- Binding Source -->
    <src:Person x:Key="myDataSource" PersonName="Joe"/>
  <!-- Binding Target -->
  <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}" />

The preceding markup declaratively binds the Text property of a TextBlock to the PersonName property of a Person object, which is given an initial value of "Joe".

Data binding in WPF also provides support for more complex services, which include validation, sorting, and grouping. Also, data binding provides the infrastructure that supports data templating, which enables you to easily create customized visualizations for bound data beyond those that the standard controls show by default.

For more information, see Data Binding Overview. For an introductory sample, see Data Binding Demo.


Although WPF provides a common set of elements and controls for you to build your applications with, it also provides powerful support for extending, customizing, and reusing elements and controls to meet your needs. This makes it easier to create custom appearances with creating wholly new controls or elements.


Multiple controls in an application frequently share the same type of objects and values, such as fonts, background colors, control templates, data templates, and styles. WPF provides an infrastructure that is known as user interface (UI) resources that allows you to define objects and values once and reuse them multiple times. The following example shows how to define a common background color that two buttons share.

    <SolidColorBrush x:Key="defaultBackground" Color="Red" />
  < StackPanel>
    <Button Background="{StaticResource defaultBackground}">One Button</Button>
    <Label Background="{StaticResource defaultBackground}">One Label</Label>

Resources can be scoped to a particular control, to all the controls on a particular page or window, or to all the controls in an application. Resources are resolved in that order. This makes it easy to manage reusable objects and values.

For more information, see Resources Overview. For an introductory sample, see Application Resources Sample.


Styles are one of several WPF customization features that enable an application, document, or UI designer to standardize on a particular look for their product. An author or designer can customize a look extensively on an application-by-application basis; however, a strong style model is required to enable maintenance and sharing of a look. WPF provides that model, which relies on the Style element. The following example shows how to create a style that sets the Background property for a TextBlock to Yellow.

<Style TargetType="{x:Type Button}">
  <Setter Property="Background" Value="Yellow"/>

For more information, see Styling and Templating. For an introductory sample, see Introduction to Styling and Templating Sample.

Control Templates

By default, WPF elements, like buttons, are constructed from sets of other elements. For example, a button is composed of three child elements that create the default button appearance. However, by using control templates, you can replace the default appearance of a WPF element while you retain its behavior. The following example shows how to change the appearance of a button by using a control template.

 <Button Content="Not Pressed">
    <ControlTemplate TargetType="{x:Type Button}">
      <Border x:Name="border" CornerRadius="80" Background="LightBlue">
        <ContentPresenter Name="content" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="border" Property="Background" Value="Aqua" />
          <Setter TargetName="content" Property="Content" Value="Pressed" />

The following illustration shows the result of using a control template to change the appearance of a button.

For more information, see ControlTemplate. For an introductory sample, see Styling with ControlTemplates Sample.

Data Templates

Although control templates let you completely replace the appearance of a control, data templates let you replace the appearance of the content of a control. Data templates are frequently used to change the default visualization of bound data.

For example, the following illustration shows the default appearance for a ListBox that is bound to a collection of Image objects.

Data templating sample screen shot

Instead of showing a list of image paths, a more visually appealing application might show a list of the actual images. The following example shows a data template that does just that.

<DataTemplate x:Key="myTaskTemplate">
  <Border Name="border" BorderBrush="Aqua" BorderThickness="1"
          Padding="5" Margin="5">
        <ColumnDefinition />
        <ColumnDefinition />
      <TextBlock Grid.Row="0" Grid.Column="0" Text="Task Name:"/>
      <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}" />
      <TextBlock Grid.Row="1" Grid.Column="0" Text="Description:"/>
      <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/>
      <TextBlock Grid.Row="2" Grid.Column="0" Text="Prioirty:"/>
      <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/>

The following illustration shows the result of this example, which still produces a list that has the same basic list support.

Data templating sample screen shot

For more information, see Data Templating Overview. For an introductory sample, see Introduction to Styling and Templating Sample.


A typical WPF application might have multiple user interface (UI) resources that are applied throughout the application. Collectively, this set of resources can be considered the theme for the application. WPF provides support for packaging user interface (UI) resources as a theme by using a resource dictionary that is encapsulated as the ResourceDictionary class.

You can define resource dictionaries as individual files that enable you to reuse a theme across multiple applications. You can also create swappable themes by defining multiple resource dictionaries that provide the same types of resources but with different values. The following example uses a resource dictionary to package user interface (UI) resources into a theme.

 <!-- Blue Theme (BlueThemeResourceDictionary.xaml) -->
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Blue" />
<!-- Yellow Theme (YellowThemeResourceDictionary.xaml) -->
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Yellow" />

For more information, see ResourceDictionary. For an introductory sample, see Themed Application Sample.

Layout and Panels

When you create UI in order to visualize data, the composition process requires controls and elements to be appropriately positioned and sized, or laid out. The WPF layout system makes the composition process easier and augments it with the ability to adapt to changes in window resizing, screen resolution, and dots per inch. The cornerstone of this flexibility is the ability to lay out UIs using relative positioning.

Instead of requiring developers to write code to make this happen, WPF provides a first-class extensible layout system that enables an easy, rapid UI development and supports globalization of UIs.

WPF delivers layout support through a common infrastructure that includes the following set of layout controls: Canvas, DockPanel, Grid, StackPanel, VirtualizingStackPanel, and WrapPanel.

The following illustration shows a DockPanel that is used to provide the layout framework for a page.

DockPanel page

The following example shows how to create the dock panel in this illustration.

    <Style TargetType="{x:Type Border}">
      <Setter Property="BorderBrush" Value="Black" />
      <Setter Property="BorderThickness" Value="1" />
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Margin" Value="5" />
      <Setter Property="FontWeight" Value="Medium" />
  <Border Background="SkyBlue" DockPanel.Dock="Top">
    <TextBlock>Dock = "Top"</TextBlock>
  <Border Background="SkyBlue" DockPanel.Dock="Top">
    <TextBlock>Dock = "Top"</TextBlock>
  <Border Background="PaleGoldenrod" DockPanel.Dock="Bottom">
    <TextBlock>Dock = "Bottom"</TextBlock>
  <Border Background="PaleGreen" DockPanel.Dock="Left">
    <TextBlock>Dock = "Left"</TextBlock>
  <Border Background="White">
    <TextBlock>This content "Fills" the remaining, unallocated space.</TextBlock>

For more information, see The Layout System. For an introductory sample, see WPF Layout Gallery Sample.


WPF introduces Windows developers to new graphics features that have the following benefits:

  • Resolution and device-independent graphics. The WPF graphics system uses device-independent units to enable resolution and device independence. Each device independent pixel automatically scales with the dots-per-inch setting of your system.

  • Improved precision. The WPF coordinate system uses doubles instead of floats. Transformations and opacity values are also expressed by using doubles. WPF also supports a wider color gamut (scRGB) and provides integrated support for managing inputs from different color spaces.

  • Advanced graphics and animation support. WPF simplifies graphics programming by managing the scene graph for you; no more worrying about scene processing, rendering loops, and bilinear interpolation. WPF provides hit-testing support, an integrated animation system, and full alpha compositing support.

  • Hardware acceleration. The WPF graphics system is designed to take advantage of graphics hardware to minimize CPU usage.

2-D Shapes

WPF provides a library of commonly used, vector-drawn 2-D shapes, such as rectangles and ellipses, which the following illustration shows.

Ellipses and rectangles

These intrinsic WPF shapes are not just shapes: they are programmable elements that implement many of the features that you expect from most common controls, which include keyboard and mouse input.

  x:Class="Window1" >
  <Ellipse Fill="LightBlue" MouseUp="ellipseButton_MouseUp" />
public partial class Window1  : Window
    void ellipseButton_MouseUp(object sender, MouseButtonEventArgs e)
        MessageBox.Show("Me, a simple ellipse, was mouse clicked!");

The following illustration shows the output for the preceding XAML markup and code-behind.

For more information, see Shapes and Basic Drawing in WPF Overview. For an introductory sample, see Shape Elements Sample.

2-D Geometries

When the 2-D shapes that WPF provides are not sufficient, you can use WPF support for geometries and paths to create your own. The following illustration shows how you can use geometries to create shapes, as a drawing brush, and to clip other WPF elements.

For more information, see Geometry Overview. For an introductory sample, see Geometries Sample.

2-D Effects

WPF provides a library of 2-D classes that you can use to create a variety of effects. The 2-D rendering capability of WPF provides the ability to paint UI elements with gradients, bitmaps, drawings, and videos; and to manipulate them by using rotation, scaling, and skewing. The following illustration gives an example of the many effects you can achieve by using WPF brushes.

Illustration of different brushes

For more information, see WPF Brushes Overview. For an introductory sample, see Brushes Sample.

3-D Rendering

WPF provides a set of 3-D rendering capabilities that integrate with 2-D graphics support in WPF in order for you to create more exciting layout, UI, and data visualization. At one end of the spectrum, WPF enables you to render 2-D images onto the surfaces of 3-D shapes, which the following illustration demonstrates.

Visual3D sample screen shot

For more information, see 3-D Graphics Overview. For an introductory sample, see 3-D Solids Sample.


Use animation to make controls and elements grow, shake, spin, and fade; and to create interesting page transitions, and more. Because WPF enables you to animate most properties, not only can you animate most WPF objects, you can also use WPF to animate custom objects that you create.

For more information, see Animation Overview. For an introductory sample, see Animation Example Gallery.


Images, video, and audio are media-rich ways of conveying information and user experiences.


Images, which include icons, backgrounds, and even parts of animations, are a core part of most applications. Because you frequently need to use images, WPF exposes the ability to work with them in a variety of ways. The following illustration shows just one of those ways.

For more information, see Imaging Overview. For an introductory sample, WPF Photo Viewer Demo.

Video and Audio

A core feature of the graphics capabilities of WPF is to provide native support for working with multimedia, which includes video and audio. The following example shows how to insert a media player into an application.

 <MediaElement Source="media\numbers.wmv" Width="450" Height="250" />

MediaElement is capable of playing both video and audio, and is extensible enough to allow the easy creation of custom UIs, like the one that is shown in the following illustration.

For more information, see WPF Graphics, Animation, and Media Overview. For an introductory sample, see Media Gallery.

Documents and Printing

WPF includes native support for working with three types of documents: fixed documents, flow documents, and XPS documents. WPF also provides a broad set of services for creating, packaging, viewing, managing, printing, and annotating documents. Much of these capabilities take advantage of WPF text and typography support.

Text and Typography

Key features in this area include support for an array of OpenType font features and the ability to easily package fonts with your application. WPF has improved quality and performance of text rendering with new ClearType enhancements and hardware acceleration. You can also more easily integrate text with other media and graphics, and you can even animate text. WPF also provides international font support, which includes a new font fallback mechanism.

For more information, see Typography in Windows Presentation Foundation. For an introductory sample, see Typography Samples.

Flow Documents

Flow documents are designed to optimize viewing and readability. Instead of being set to one predefined layout, flow documents dynamically adjust and reflow their content based on run-time variables, such as window size, device resolution, and optional user preferences.

For more information, see Flow Document Overview. For an introductory sample, see FlowDocument Properties Sample.

Fixed Documents

Fixed documents are intended for applications that require a precise "what you see is what you get" (WYSIWYG) presentation. These documents render their content independent of the display or printer hardware that is used. Typical uses for fixed documents include desktop publishing, word processing, and form layout, where adherence to the original page design is critical.

As part of its layout, a fixed document maintains the precise positional placement of content elements independent of the display or print device in use. For example, a fixed document page that is viewed on a 96 dpi display appears exactly the same when it is displayed on a 600 dpi laser printer as when it is displayed on a 4800 dpi phototypesetter. The page layout remains the same in all cases, although the document quality maximizes to the capabilities of each device.

For more information, see Documents in Windows Presentation Foundation.

XPS Documents

WPF builds on fixed documents by defining a new type of document, known as an XML Paper Specification (XPS) document, which is a paginated representation of electronic paper that is described in an XML-based format. XPS is an open, cross-platform document format that enables users to create, share, print, and archive paginated documents. XPS technology supports many uses:

  • Read, write, and store documents, which include content and resources in a single, portable, and easy-to-distribute ZipPackage based file.

  • High-fidelity rendering – documents render at the maximum quality of the printer or display.

  • Direct print spooling for Windows Vista.

  • Routing documents directly to an XPS-compatible printer.

  • Simple application integration and display with the DocumentViewer control.

The XPS Viewer application, which is shown in the following illustration, enables users to view, manage, and print XPS document files.

To work with XPS documents, WPF includes APIs for the following:

  • Integration of XPS Documents with traditional applications, the Web, and hardware.

  • Integration of packages that comply with the Open Packaging Conventions (OPC) with traditional applications and the Web.

  • Generation of XPS Documents from WPF applications.

For more information, see Documents in Windows Presentation Foundation. For an introductory sample, see Creating an XPS Document Sample.


The WPF System.IO.Packaging APIs allow your applications to organize data files, content, and resources into a single, portable, easy-to-distribute and easy-to-access ZIP file. Digital signatures can be included to authenticate items that are contained in a package and to validate that the signed item was not tampered with or modified. You can also encrypt packages by using rights management in order to restrict access to protected information.

For more information, see Documents in Windows Presentation Foundation. For samples, see Packaging Samples.


Managed code also provides better control over the print system. Printing enhancements enable real-time, remote print server and queue installation. They also enable dynamic discovery of the printer capabilities and dynamic setting of printer options. In some situations, IT managers can fix print system problems without leaving their desks. For example, they can reroute or reprioritize a print job that is stuck in a busy print queue.

Additionally, XPS documents have enhanced capabilities for printing. The existing Microsoft Windows Graphics Device Interface (GDI) print path typically requires the conversion of a document into a print processor format, such as Enhanced Metafile (EMF), and then requires a second conversion into the page description language of the printer, such as Printer Control Language (PCL) or PostScript. To make spool files smaller and to reduce network load to networked printers, XPS can be printed without conversion, because the XPS file format is, in part, a print processor language and a page description language.

For more information, see Printing Overview. For an introductory sample, see Printing an XPS Document.


Annotations are notes or comments that people add to documents to flag information or to highlight items of interest for later reference. Although writing notes on printed documents is easy and commonplace, the ability to add personal comments to online documents is typically limited or unavailable. WPF provides a framework for annotations that supports Sticky Notes and highlights, which can be applied to documents that are hosted in the DocumentViewer control, as the following illustration shows.

Annotation styling

For more information, see Annotations Overview. For an introductory sample, see Document Serialization Sample.

WPF Applications

WPF has an extensive range of support for visualizing and interacting with data. To deliver these experiences, WPF has a special group of classes that are collectively known as the application model. The application model provides the machinery to deliver content to users, and includes the ability to define and manage applications, whether they are stand-alone applications that are built from windows and dialog boxes, or browser-hosted applications that are built from pages, hyperlinks, and frames, or a combination of both.

Application Infrastructure

A variety of application infrastructure needs to be established before an application can actually do anything useful, such as display windows or browse to pages. As with any Windows application, this includes creating an entry point function, starting a windows message loop, and creating a main UI thread. In WPF, you can create this infrastructure in two steps:

  1. Create a .xaml file with the following XAML markup:

      xmlns="" />
  2. Configure the file as an Microsoft build engine (MSBuild) ApplicationDefinition item.

An application that is compiled with just this will launch and run, like any standard Windows application, with a single instance of the Application class managing the application, its lifetime, shared access to properties and resources, and a host of features for window and navigation management.

For more information, see Application Management Overview.

Stand-alone Applications

As you would expect, WPF provides a class to create and show windows and dialog boxes.

    Title="Hello, WPF Window!" Height="300" Width="300">
  <!-- Content Goes Here -->
public partial class WPFWindow : System.Windows.Window
    public WPFWindow()

To show this window, you can update the application definition with the name of the window .xaml file to open when the application first starts:

  StartupUri="WPFWindow.xaml" />

Application not only provides an easy way to show a window, it also tracks all windows, it remembers the main window, and its lifetime can be configured to end based on the lifetime of its windows.

For more information, see Windows Presentation Foundation Windows Overview.


Application models, WPF, and traditional presentation technologies differ in the ways they provide support for navigation. To begin with, WPF provides the basic elements of any navigation framework: Page, Hyperlink, and Frame. You can use XAML to assemble these elements as you would on a typical HTML page, although with the richness of WPF.

You can then host these basic navigational elements in Windows Internet Explorer 7 as either stand-alone .xaml pages, or as pages with code that you can compile into special types of applications that are known as XAML browser applications (XBAPs). These applications run directly from Windows Internet Explorer 7, as the following illustration shows.

ExpenseIt sample screen shot (Create Report page)

In addition, the same basic navigation elements can be injected into stand-alone applications. WPF implements a special type of window, NavigationWindow, that can host page content just like a browser. Also, you can incorporate the dual-purpose Frame control into window or page content that is hosted in a stand-alone application.

With these elements and more, you can create a variety of user experiences out of the box, which were previously non-trivial to create, including wizards and Web applications that run on the client.

For more information, see Navigation Overview.


Because you are likely to run some of your WPF applications from Internet Explorer 7, security is a first class citizen. Essentially, browser-hosted applications run in a security sandbox that is provided the same set of access to a user's computer as any typical Web application. Also, many WPF classes operate safely in this security sandbox, which enables you to build most of the application types that you can build when you have complete access to the local computer.

For more information, see Windows Presentation Foundation Security.

Additional Features

See Also