Home > Articles > Home & Office Computing > Microsoft Windows Desktop

Introduction to Windows Presentation Foundation

Windows Presentation Foundation (WPF) represents a major step forward in user interface technology. This chapter lays out some of the basic principles of WPF and walk through a quick overview of the entire platform.
This chapter is from the book

WPF as the New GUI

Before we dive into WPF proper, it is interesting to consider where we're coming from.

User32, à la Charles Petzold

Anyone programming to User32 has, at some point, read one of Petzold's "Programming Windows" books. They all start with an example something like this:

#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd,
             UINT msg,
             WPARAM wparam,
             LPARAM lparam);
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
         LPSTR cmdline, int cmdshow) {
  MSG         msg;
  HWND        hwnd;
  WNDCLASSEX  wndclass = { 0 };
  wndclass.cbSize          = sizeof(WNDCLASSEX);
  wndclass.style           = CS_HREDRAW | CS_VREDRAW;
  wndclass.lpfnWndProc     = WndProc;
  wndclass.hIcon           = LoadIcon(NULL, IDI_APPLICATION);
  wndclass.hCursor         = LoadCursor(NULL, IDC_ARROW);
  wndclass.hbrBackground   = (HBRUSH)GetStockObject(WHITE_BRUSH);
  wndclass.lpszClassName   = TEXT("Window1");
  wndclass.hInstance       = hInstance;
  wndclass.hIconSm         = LoadIcon(NULL, IDI_APPLICATION);
  RegisterClassEx(&wndclass);
  hwnd = CreateWindow(TEXT("Window1"),
        TEXT("Hello World"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        0,
        CW_USEDEFAULT,
        0,
        NULL,
        NULL,
        hInstance,
        NULL);

  if( !hwnd )
    return 0;
  ShowWindow(hwnd, SW_SHOWNORMAL);
  UpdateWindow(hwnd);
  while( GetMessage(&msg, NULL, 0, 0) ) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
         WPARAM wparam, LPARAM lparam) {
  switch(msg) {
    case WM_DESTROY:
      PostQuitMessage(WM_QUIT);
      break;
    default:
      return DefWindowProc(hwnd, msg, wparam, lparam);
  }
  return 0;
}

This is "Hello World" when talking to User32. There are some very interesting things going on here. A specialized type (Window1) is first defined by the calling of RegisterClassEx, then instantiated (CreateWindow) and displayed (ShowWindow). Finally, a message loop is run to let the window receive user input and events from the system (GetMessage, TranslateMessage, and DispatchMessage). This program is largely unchanged from the original introduction of User back in the Windows 1.0 days.

Windows Forms took this complex programming model and produced a clean managed object model on top of the system, making it far simpler to program. Hello World can be written in Windows Forms with ten lines of code:

using System.Windows.Forms;
using System;

class Program {
  [STAThread]
  static void Main() {
    Form f = new Form();
    f.Text = "Hello World";
    Application.Run(f);
  }
}

A primary goal of WPF is to preserve as much developer knowledge as possible. Even though WPF is a new presentation system completely different from Windows Forms, we can write the equivalent program in WPF with very similar code1 (changes are in boldface):

using System.Windows;
using System;

class Program {
  [STAThread]
  static void Main() {
    Window f = new Window();
    f.Title  = "Hello World";
    new Application().Run(f);
  }
}

In both cases the call to Run on the Application object is the replacement for the message loop, and the standard CLR (Common Language Runtime) type system is used for defining instances and types. Windows Forms is really a managed layer on top of User32, and it is therefore limited to only the fundamental features that User32 provides.

User32 is a great 2D widget platform. It is based on an on-demand, clip-based painting system; that is, when a widget needs to be displayed, the system calls back to the user code (on demand) to paint within a bounding box that it protects (with clipping). The great thing about clip-based painting systems is that they're fast; no memory is wasted on buffering the content of a widget, nor are any cycles wasted on painting anything but the widget that has been changed.

The downsides of on-demand, clip-based painting systems relate mainly to responsiveness and composition. In the first case, because the system has to call back to user code to paint anything, often one component may prevent other components from painting. This problem is evident in Windows when an application hangs and goes white, or stops painting correctly. In the second case, it is extremely difficult to have a single pixel affected by two components, yet that capability is desirable in many scenarios—for example, partial opacity, anti-aliasing, and shadows.

With overlapping Windows Forms controls, the downsides of this system become clear (Figure 1.1). When the controls overlap, the system needs to clip each one. Notice the gray area around the word linkLabel1 in Figure 1.1.

Figure 1.1

Figure 1.1 Windows Forms controls overlapping. Notice that each control obscures the others.

WPF is based on a retained-mode composition system. For each component a list of drawing instructions is maintained, allowing for the system to automatically render the contents of any widget without interacting with user code. In addition, the system is implemented with a painter's algorithm, which ensures that overlapping widgets are painted from back to front, allowing them to paint on top of each other. This model lets the system manage the graphics resource, in much the same way that the CLR manages memory, to achieve some great effects. The system can perform high-speed animations, send drawing instructions to another machine, or even project the display onto 3D surfaces—all without the widget being aware of the complexity.

To see these effects, compare Figures 1.1 and 1.2. In Figure 1.2 the opacity on all the WPF controls is set so that they're partially transparent, even to the background image.

Figure 1.2

Figure 1.2 WPF controls overlapping, with opacity set to semitransparency. Notice that all the controls compositing together are visible, including the background image.

WPF's composition system is, at its heart, a vector-based system, meaning that all painting is done through a series of lines. Figure 1.3 shows how vector graphics compare to traditional raster graphics.

Figure 1.3

Figure 1.3 Comparing vector and raster graphics. Notice that zooming in on a vector graphic does not reduce its crispness.

The system also supports complete transform models, with scale, rotation, and skew. As Figure 1.4 shows, any transformation can be applied to any control, producing bizarre effects even while keeping the controls live and usable.

Figure 1.4

Figure 1.4 WPF controls with a variety of transformations applied. Despite the transformations, these controls remain fully functional.

Note that when User32 and GDI32 were developed, there was really no notion of container nesting. The design principle was that a flat list of children existed under a single parent window. The concept worked well for the simple dialogs of the 1990s, but today's complex user interfaces require nesting. The simplest example of this problem is the GroupBox control. In the User32 design, GroupBox is behind controls but doesn't contain them. Windows Forms does support nesting, but that feature has revealed many problems with the underlying User32 model of control.

In WPF's composition engine, all controls are contained, grouped, and composited. A button in WPF is actually made up of several smaller controls. This move to embrace composition, coupled with a vector-based approach, enables any level of containment (Figure 1.5).

Figure 1.5

Figure 1.5 WPF controls are built out of composition and containment. The button shown here contains both text and an image.

To really see the power of this composition, examine Figure 1.6. At the maximum zoom shown, the entire circle represents less than a pixel on the original button. The button actually contains a vector image that contains a complete text document that contains a button that contains another image.

Figure 1.6

Figure 1.6 The power of composition, as revealed by zooming in on the composite button shown in Figure 1.5

In addition to addressing the limitations of User32 and GDI32, one of WPF's goals was to bring many of the best features from the Web programming model to Windows developers.

HTML, a.k.a. the Web

One of the biggest assets of Web development is a simple entry to creating content. The most basic HTML "program" is really nothing more than a few HTML tags in a text file:

<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <p>Welcome to my document!</p>
  </body>
</html>

In fact, all of these tags can be omitted, and we can simply create a file with the text "Welcome to my document!", name it <something>.html, and view it in a browser (Figure 1.7). This amazingly low barrier to entry has made developers out of millions of people who never thought they could program anything.

Figure 1.7

Figure 1.7 Displaying a simple HTML document in Internet Explorer

In WPF we can accomplish the same thing using a new markup format called XAML (Extensible Application Markup Language), pronounced "zammel." Because XAML is a dialect of XML, it requires a slightly stricter syntax. Probably the most obvious requirement is that the xmlns directive must be used to associate the namespace with each tag:

<FlowDocument
  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>

  <Paragraph>Welcome to my document!</Paragraph>
</FlowDocument>

You can view the file by double-clicking <something>.xaml (Figure 1.8).

Figure 1.8

Figure 1.8 Displaying a WPF document in Internet Explorer

Of course, we can leverage all the power of WPF in this simple markup. We can trivially implement the button display from Figure 1.5 using markup, and display it in the browser (Figure 1.9).

Figure 1.9

Figure 1.9 Displaying a WPF document in Internet Explorer using controls and layout from WPF

One of the big limitations of the HTML model is that it really only works for creating applications that are hosted in the browser. With XAML markup, either we can use it in a loose markup format and host it in the browser, as we have just seen, or we can compile it into an application and create a standard Windows application using markup (Figure 1.10):

Figure 1.10

Figure 1.10 Running an application authored in XAML. The program can be run in a top-level window or hosted in a browser.

<Window
  xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
  Title='Hello World!'>

  <Button>Hello World!</Button>
</Window>

Programming capability in HTML comes in three flavors: declarative, scripting, and server-side. Declarative programming is something that many people don't think of as programming. We can define behavior in HTML with simple markup tags like <form /> that let us perform actions (generally posting data back to the server). Script programming lets us use JavaScript to program against the HTML Document Object Model (DOM). Script programming is becoming much more fashionable because now enough browsers have support for a common scripting model to make scripts run everywhere. Server-side programming lets us write logic on the server that interacts with the user (in the Microsoft platform, that means ASP.NET programming).

ASP.NET provides a very nice way to generate HTML content. Using repeaters, data binding, and event handlers, we can write simple server-side code to create simple applications. One of the more trivial examples is simple markup injection:

<%@ Page %>
<html>
  <body>
    <p><%=DateTime.Now().ToString()%></p>
  </body>
</html>

The real power of ASP.NET comes in the rich library of server controls and services. Using a single control like DataGrid, we can generate reams of HTML content; and with services like membership we can create Web sites with authentication easily.

The big limitation of this model is the requirement to be online. Modern applications are expected to run offline or in occasionally connected scenarios. WPF takes many of the features from ASP.NET—repeaters and data binding, for example—and gives them to Windows developers with the additional ability to run offline.

One of the primary objectives of WPF was to bring together the best features of both Windows development and the Web model. Before we look at the features of WPF, it is important to understand the new programming model in the .NET Framework 3.0: XAML.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020