Read an Excerpt
WPF Programmer's ReferenceWindows Presentation Foundation with C# 2010 and .NET 4
By Rod Stephens
John Wiley & SonsCopyright © 2010 John Wiley & Sons, Ltd
All right reserved.
Chapter OneWPF Overview
This chapter explains fundamental Windows Presentation Foundation (WPF) concepts. Normally, it's the glaringly obvious chapter that you skip to get to the good stuff. If this were a cookbook, this would be where I explain food and tell you why it's important ("so you don't starve").
In this case, however, I encourage you to at least skim this chapter before plunging ahead. Many parts of WPF are confusing and seemingly inconsistent. This chapter gives some useful background on what WPF is (that question has caused more confusion than you might imagine), WPF's goals, and the underlying architecture used by WPF.
These tidbits of information will give you some useful perspective for understanding WPF's quirks and idiosyncrasies. For example, this information will let you say, "Oh, WPF does it that way because Direct3D does it that way" or "I'll bet this weird behavior was provided to save me a few keystrokes of typing."
In addition to this background, this chapter describes the basic types of WPF projects.
Finally, this chapter can help you understand what's contained in the later chapters. This chapter briefly defines resources, styles, control templates, and other terms that are described more completely in later chapters. A quick introduction to those terms now will help you know which chapters to read later.
WPF IN A NUTSHELL
WPF has been around for quite a while now, but there are still plenty of people out there who don't really know what it is. I've heard people claim it's everything from a set of controls to a "Vista thing" to XAML.
In fact, there's a kernel of truth in each of these attitudes. WPF does include a new set of controls that largely replace the Windows Forms controls. The libraries you need to run WPF applications are installed by default in Vista and Windows 7, so it is sort of a Vista thing, although you can also run WPF applications in Windows XP and certainly in future versions of Windows (and perhaps even UNIX some day). WPF applications can use XAML to build interfaces, and XAML is all you really need to write loose web pages; but there's a lot more to WPF than just XAML.
As far as WPF's importance and usefulness go, opinions range the gamut from "I don't have time for jiggling buttons and spinning labels" to "It's the wave of the future, and every new application will be written in WPF by the end of the year" (although that was last year, so perhaps this latter attitude isn't quite correct).
Again, the truth lies somewhere between these two extremes. You certainly can abuse WPF to build completely unusable interfaces full of bouncing buttons, skewed video, stretched labels, garish colors, and rotating three-dimensional (3D) graphics. You can add animation to the controls until the interface behaves more like a video game than a business application.
Figure 1-1 shows the Clutter example program displaying a (faked) series of rotated images as an invoice spins into view. This program demonstrates some interesting techniques but goes way overboard with gratuitous animation, displaying a spinning invoice area, animated buttons, and sound effects. If you think it's ugly in this book, you should see how annoying it is when you run it!
If you use restraint and good design principles, you can use WPF to make user interfaces that are more visually appealing and inviting. You can use animation to hide and display information to reduce clutter while giving the user hints about where the data has gone so it's easy to find later.
It may not be true that all new applications will use WPF by the end of the year, but you should consider using WPF for new development. While getting the most out of WPF takes a lot of study and practice, it's easy enough to use WPF controls instead of the corresponding Windows Forms controls in most cases. You may not stretch WPF to its limits, but you can take advantage of some of WPF's new features without a lot of work.
Of course, some applications will probably never need WPF. Some programs run most naturally as automatic services or from the command line and don't need graphical user interfaces at all.
What is WPF?
So, what exactly is WPF? I've heard it described as a library, framework, subsystem, set of controls, language, and programming model.
Probably the easiest way to understand WPF is to think of it as an assortment of objects that make it easier to build cool user interfaces. Those objects include a new set of controls, some replacing your favorite Windows Forms controls (such as Label, TextBox, Button, Slider) and others providing new features (such as Expander, FlowDocument, and ViewBox).
WPF also includes an abundance of new objects to manage animation, resources, events, styles, templates, and other new WPF features.
Your application uses some combination of these objects to build a user interface.
What is XAML?
XAML (pronounced zammel) stands for "eXtensible Application Markup Language." It is an extension of XML (eXtensible Markup Language). Microsoft invented XAML to represent WPF user interfaces in a static language much as HTML represents the contents of a web page. It defines special tokens to represent windows, controls, resources, styles, and other WPF objects.
A program can use a file containing XAML code to load a user interface. For example, a web browser can load a file containing XAML code and display the user interface (UI) it defines. If you use Expression Blend or Visual Studio to create a WPF application, the application automatically loads the project's XAML for you so you don't need to add code to do that yourself.
All of the usual XML rules apply to XAML files. In particular, XAML files must have a single root element that contains all of the other elements in the file. What element you use as the root element depends on the type of project you are building.
For example, in a compiled application, the root element is a Window that represents the window displayed on the desktop. In contrast, a loose XAML page is displayed in a web browser, so the browser plays the role of the window. In that case, the root element is typically some container control such as a Grid or StackPanel that can hold all of the other elements.
Each opening element must have a corresponding closing element with the same name but beginning with a slash. For example, the following code snippet defines a StackPanel:
If an element doesn't need to contain any other elements, you can use a special shorthand and end the opening element with a slash instead of a separate closing element. The following snippet shows an Image object. It doesn't contain any other items, so it uses the shorthand notation.
The preceding snippet also demonstrates attributes. A XAML attribute is a value contained inside an item's opening tag. In this snippet, the Image object has attributes Margin, Width, Height, and Source with values 10, 75, 75, and Volleyball.jpg.
XAML elements must be properly nested to show which WPF objects contain other objects. The following XAML code shows a Window that contains a horizontal StackPanel that holds several other vertical StackPanel objects, each holding an Image and a Label.
Figure 1-2 shows the result.
Figure 1-3 shows the program with its StackPanels highlighted so they are easy to see. In this figure, you can see how the outer StackPanel arranges the inner StackPanels horizontally and how the inner StackPanels arrange their Images and Labels vertically.
The controls that make up a user interface such as the one shown in Figure 1-2 form a natural hierarchy with some controls containing others, which may then contain others. Figure 1-4 shows this program's control hierarchy graphically.
WPF has two concepts of trees that represent structure similar to the one shown in Figure 1-4. Normally, you don't need to worry explicitly about these, but knowing what they are can make it a bit easier to understand some of the online documentation.
The logical tree is defined by the content relationships among the objects in the interface. That includes controls contained within other controls (such as a series of Image controls contained within a StackPanel) and simple content (such as the string contained in a Label).
It also includes some objects that you may not think of as separate entities. For example, if you add items to a ListBox, those items are automatically added as ListBoxItem objects inside the ListBox. If you use the Expression Blend or Visual Studio editors to add the items, you may not think of them as separate objects, but they are, as far as the logical tree is concerned.
The second WPF tree is the visual tree. The visual tree represents the structure of visual objects including the components that define them. For example, a scrollbar includes a draggable thumb, two arrow buttons at the ends, and two clickable areas between the thumb and the arrows. Each of those pieces is a separate object that is wrapped up inside a scrollbar, and each of the pieces is part of the visual tree.
Why should you care about the logical and visual trees? First, controls tend to inherit property values according to their positions in the logical tree. For example, the preceding XAML code used the following attributes to set the main Window's FontSize, FontWeight, and FontFamily properties.
FontSize="22" FontWeight="Bold" FontFamily="Comic Sans MS"
These properties are inherited throughout the logical tree so the Labels at the bottom of the tree all use these font values.
The second reason you should care about these trees is that events tend to follow the visual tree. For example, when you click on an arrow in a scrollbar, you don't really want to have to deal with that arrow's events. Instead you can let the event propagate up through the visual tree to the scrollbar, and you can catch it there.
Because the controls that make up a user interface such as this one naturally form a containment hierarchy, they map fairly reasonably into XML. Unfortunately some of the things that make up an interface don't fit quite as neatly in a tree structure.
For example, Figure 1-5 shows a more complicated version of the previous user interface.
In this version, all of the Image controls have drop shadows. You could give each Image its own drop shadow, but that would mean duplicating code, which would make maintaining the program harder. For example, if you later decided to remove the drop shadows or use some other bitmap effect (perhaps to put a glow around the images), you would have to update each control separately.
Rather than repeating the drop shadow code, you can define a Style and apply it to each Image. Now to change every Image, you only need to change the Style.
Similarly, this example defines a style for its Label controls that gives them drop shadows, makes them yellow, and centers their text.
Unfortunately, each of these styles applies to several different controls in the logical hierarchy, and that messes up the nice neat tree structure shown in Figure 1-4.
XAML still uses a hierarchical XML structure anyway, even though some scenarios such as this one require objects to refer to others in a non-hierarchical way. It works, but, as you'll see in later chapters, it does complicate the XAML syntax considerably.
What is silverlight?
Silverlight (formerly known as WPF/e, where the e stands for "everywhere") is a restricted version of WPF designed to run safely in a browser while still providing a rich user interface. It runs on most major browsers including Mozilla Firefox, Microsoft Internet Explorer, and Apple Safari.
To minimize library size and to work safely in the browser, Silverlight does not provide all of the features that are included in WPF. Some features are missing, while others are provided in a restricted way. While there are some differences between WPF and Silverlight, the basics are the same; so much of what you learn about WPF applies to Silverlight as well.
There are several differences between WPF and Silverlight, but so far Microsoft has not published an authoritative list. Here are some of the restrictions in Silverlight:
* Once assigned, you cannot change a control's style. * You must explicitly assign each control's style. You cannot create a style that applies to every control of a given type (e.g., buttons). * One style cannot inherit from another. * You cannot put triggers in styles and templates. * You cannot use dynamic resources. All resources are static. * Silverlight has more restrictive data binding. * Access to Windows API functions is limited. * You cannot use commands in Silverlight. * Silverlight doesn't support 3D graphics and graphics hardware. * Silverlight doesn't include preview (tunneling) events.
This list will change over time (it may even be outdated by the time you read this). Microsoft is trying to include as many WPF features as possible in Silverlight, while still keeping the necessary libraries as small as possible.
WPF lets you build three main kinds of applications: stand-alone, XAML Browser Applications, and loose XAML pages.
A stand-alone application is compiled and runs locally on the user's computer much as any stand-alone application does. This type of application runs with full trust and has full access to the computer. It can read and write files, modify the System Registry, and do just about anything else that you can do from a C# or Visual Basic program.
A XAML Browser Application (XBAP - pronounced ex-bap) is a compiled application that runs within a web browser. For security purposes, it runs within the Internet Zone so it doesn't have full trust and cannot access all of the parts of the computer that are available to a stand-alone application. XBAPs can only run in browsers that support them (currently Internet Explorer and Firefox) and require that the .NET Framework version 3 or later be installed on the user's computer.
Loose XAML pages are simply XAML files displayed in a web browser. They can be viewed by any web browser that understands XAML. Loose XAML pages do not require the .NET Framework to be installed on the user's computer, so they can run on operating systems that cannot install the .NET Framework, such as Macintosh and UNIX systems. Loose XAML pages cannot use script, C#, or Visual Basic code, however. They can display interesting graphics and let the user manipulate the display through XAML animations, but they don't have the power of the other kinds of applications.
In addition to these different types of applications, WPF provides several different navigation models for stand-alone applications and XBAPs. First, they can provide navigational tools similar to those used by Windows Forms applications. Buttons, links, and other code-based mechanisms can display other pages and windows.
Excerpted from WPF Programmer's Reference by Rod Stephens Copyright © 2010 by John Wiley & Sons, Ltd. Excerpted by permission.
All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.