A Tour of WPF
When I started writing this book, I wanted to make it as short as possible, but no shorter (my apologies to Dr. Einstein). Even with that philosophy, I wanted to give you, the reader, a quick overview of the platform to provide a grounding in all the basic concepts you need to get started.
Getting Up and Running
There are many ways to approach WPF: from the browser, from markup, or from code. I've been programming for so long that I can't help but start from a simple C# program. Every WPF application starts with the creation of an Application object. The Application object controls the lifetime of the application and is responsible for delivering events and messages to the running program.
In addition to the Application object, most programs want to display something to a human. In WPF that means creating a window.5 We've already seen the basic WPF application source code, so this should come as no surprise to you:
using System.Windows; using System; class Program { [STAThread] static void Main() { Application app = new Application(); Window w = new Window(); w.Title = "Hello World"; app.Run(w); } }
To compile this code, we need to invoke the C# compiler. We have two options; the first is to directly invoke the C# compiler on the command line. We must include three reference assemblies to compile against WPF. The locations of the tools for building WPF applications depend on how they were installed. The following example shows how to compile this program if the .NET Framework 3.0 SDK has been installed and we're running in the build window provided:
csc /r:"%ReferenceAssemblies%"\WindowsBase.dll /r:"%ReferenceAssemblies%"\PresentationCore.dll /r:"%ReferenceAssemblies%"\PresentationFramework.dll /t:winexe /out:bin\debug\tour.exe program.cs
Compiling with C# directly works great for a single file and a couple of references. A better option, however, is to use the new build engine included with the .NET Framework 3.0 SDK and Visual Studio 2005: MSBuild. Creating an MSBuild project file is relatively simple. Here we convert the command line into a project file:
<Project DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <Configuration>Debug</Configuration> <Platform>AnyCPU</Platform> <RootNamespace>Tour</RootNamespace> <AssemblyName>Tour</AssemblyName> <OutputType>winexe</OutputType> <OutputPath>.\bin\Debug\</OutputPath> </PropertyGroup> <ItemGroup> <Reference Include='System' /> <Reference Include='WindowsBase' /> <Reference Include='PresentationCore' /> <Reference Include='PresentationFramework' /> </ItemGroup> <ItemGroup> <Compile Include='program.cs' /> </ItemGroup> <Import Project='$(MSBuildBinPath)\Microsoft.CSharp.targets' /> <Import Project='$(MSBuildBinPath)\Microsoft.WinFX.targets' /> </Project>
To compile the application, we can now invoke MSBuild at the command line:
msbuild tour.csproj
Running the application will display the window shown in Figure 1.11.
Figure 1.11 Empty window created in an application
With our program up and running, we can think about how to build something interesting. One of the most visible changes in WPF (at least to the developer community) is the deep integration of markup in the platform. Using XAML to build an application is generally much simpler.
Moving to Markup
To build our program using markup, we will start by defining the Application object. We can create a new XAML file, called App.xaml, with the following content:
<Application xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' />
As before, it isn't very interesting to run. We can define a window using the MainWindow property of Application:
<Application xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'> <Application.MainWindow> <Window Title='Hello World' Visibility='Visible' /> </Application.MainWindow> </Application>
To compile this code, we need to update our project file to include the application definition:
<Project ...> ... <ItemGroup> <ApplicationDefinition Include='app.xaml' /> </ItemGroup> ... </Project>
If we were to build now, we would get an error because, by including our application definition, we have automatically defined a "Main" function that conflicts with the existing program.cs. So we can remove program.cs from the list of items in the project, and we are left with just the application definition. At this point, running the application produces exactly the same result as Figure 1.11 shows.
Instead of defining our window inside of the application definition, it is normal to define new types in separate XAML files. We can move the window definition into a separate file, MyWindow.xaml:
<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > </Window>
We can then update the application definition to refer to this markup:
<Application xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' StartupUri='MyWindow.xaml' />
Finally, we need to add the window to the project file. For any compiled markup (except the application definition), we use the Page build type:
<Project ...> ... <ItemGroup> <Page Include='mywindow.xaml' /> <ApplicationDefinition Include='app.xaml' /> </ItemGroup> ... </Project>
Now we have a basic program up and running, well factored, and ready to explore WPF.
The Basics
Applications in WPF consist of many controls, composited together. The Window object that we have already seen is the first example of one of these controls. One of the more familiar controls is Button:
<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <Button>Howdy!</Button> </Window>
Running this code will produce something like Figure 1.12. The first interesting thing to notice here is that the button automatically fills the entire area of the window. If the window is resized, the button continues to fill the space.
Figure 1.12 A simple button in a window
All controls in WPF have a certain type of layout. In the layout for a window, a single child control fills the window. To put more than one control inside of a window, we need to use some type of container control. A very common type of container control in WPF is a layout panel.
Layout panels accept multiple children and enforce some type of layout policy. Probably the simplest layout is the stack:
<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <StackPanel> <Button>Howdy!</Button> <Button>A second button</Button> </StackPanel> </Window>
StackPanel works by stacking controls one on top of another (shown in Figure 1.13).
Figure 1.13 Two buttons inside of a stack panel
A lot more controls, and a lot more layouts, are included in WPF (and, of course, you can build new ones). To look at a few other controls, we can add them to our markup:
<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <StackPanel> <Button>Howdy!</Button> <Button>A second button</Button> <TextBox>An editable text box</TextBox> <CheckBox>A check box</CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </StackPanel> </Window>
Running this code shows that you can interact with all the controls (Figure 1.14).
Figure 1.14 Several more controls added to a window
To see different layouts, we can replace StackPanel. Here we swap in WrapPanel:
<Window xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <WrapPanel> <Button>Howdy!</Button> <Button>A second button</Button> <TextBox>An editable text box</TextBox> <CheckBox>A check box</CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
Running this code reveals a noticeable difference in the layout of the controls (Figure 1.15).
Figure 1.15 Several controls inside of a wrap panel
Now that we have seen some controls, let's write some code that interacts with the controls. Associating a markup file with code requires several steps. First we must provide a class name for the markup file:
<Window x:Class='EssentialWPF.MyWindow' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <WrapPanel> <Button>Howdy!</Button> <Button>A second button</Button> <TextBox>An editable text box</TextBox> <CheckBox>A check box </CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
It is also very common to use the C# 2.0 feature of partial types to associate some additional code with the markup file. To define a code-behind file, we need to create a C# class with the same name6 that we specified in the markup file. We must also call InitializeComponent from the constructor of our class:7
using System; using System.Windows.Controls; using System.Windows; namespace EssentialWPF { public partial class MyWindow : Window { public MyWindow() { InitializeComponent(); } } }
To finish associating our code with the markup, we need to update the project file to include the newly defined C# file:
<Project ...> ... <ItemGroup> <Compile Include='mywindow.xaml.cs' /> <Page Include='mywindow.xaml' /> <ApplicationDefinition Include='app.xaml' /> </ItemGroup> ... </Project>
Because our code doesn't do anything interesting, there isn't a lot to see if we run the program. The most common link between a code-behind file and the markup file is an event handler. Controls generally expose one or more events, which can be handled in code. Handling an event requires only specifying the event handler method name in the markup file:
<Window x:Class='EssentialWPF.MyWindow' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <WrapPanel> <Button Click='HowdyClicked'>Howdy!</Button> <Button>A second button</Button> <TextBox>An editable text box</TextBox> <CheckBox>A check box </CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
We can then implement the method in the code-behind file:
using System; using System.Windows.Controls; using System.Windows; namespace EssentialWPF { public partial class MyWindow : Window { public MyWindow() { InitializeComponent(); } void HowdyClicked(object sender, RoutedEventArgs e) { } } }
To access any control from the code-behind file, we must provide a name for the control:
<Window x:Class='EssentialWPF.MyWindow' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <WrapPanel> <Button Click='HowdyClicked'>Howdy!</Button> <Button>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox>A check box </CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
We can then use the specified name in the code-behind file:
using System; using System.Windows.Controls; using System.Windows; namespace EssentialWPF { public partial class MyWindow : Window { public MyWindow() { InitializeComponent(); } void HowdyClicked(object sender, RoutedEventArgs e) { _text1.Text = "Hello from C#"; } } }
Running this application and clicking the Howdy! button reveals something like Figure 1.16.
Figure 1.16 Clicking a button to cause changes in another element
Beyond the basics of controls, layout, and events, probably the most common thing to do is have an application interact with data.
Working with Data
WPF has a deep dependency on data and data binding. A look at one of the most basic controls shows many types of binding:
Button b = new Button(); b.Content = "Hello World";
At least three types of binding are occurring here. First, the way a button is displayed is determined by a type of binding. Every control has a Resources property, which is a dictionary that can contain styles, templates, or any other type of data. Controls then can bind to these resources.
Second, the data type of the content of a button is System.Object. Button can take any data and display it. Most controls in WPF leverage what is called the content model, which, at its core, enables rich content and data presentation. For example, instead of a string, we can create buttons with almost any content.
Third, the basic implementation of both the button's display and the core content model uses data binding to wire up properties from the control to the display elements.
To get a feel for how binding works in WPF, we can look at a couple of scenarios. First let's consider setting the background of a button:
<Button Background='Red' />
If we want to share this background between multiple buttons, the simplest thing to do is to put the color definition in a common place and wire all the buttons to point at that one place. This is what the Resources property is designed for.
To define a resource, we declare the object in the Resources property of a control and assign x:Key to the object:
<Window x:Class='EssentialWPF.ResourceSample' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <!-- ... rest of window ... --> </Window>
We can then refer to a named resource using the DynamicResource or StaticResource markup extension (covered in detail in Chapter 6):
<Window x:Class='EssentialWPF.ResourceSample' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <WrapPanel> <Button Background='{StaticResource bg}' Click='HowdyClicked'>Howdy!</Button> <Button Background='{StaticResource bg}'>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox>A check box </CheckBox> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
Running this program reveals that both buttons have the same color (Figure 1.17).
Figure 1.17 Binding to a resource
Resource binding is a relatively simple type of binding. We can also bind properties between controls (and data objects) using the data-binding system. For example, we can bind the text of TextBox to the content of CheckBox:
<Window x:Class='EssentialWPF.ResourceSample' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Title='Hello World' > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <WrapPanel> <Button Background='{StaticResource bg}' Click='HowdyClicked'>Howdy!</Button> <Button Background='{StaticResource bg}'>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox Content='{Binding ElementName=_text1,Path=Text}' /> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> </Window>
When we run this code, we can type in the text box and the content of the check box will be updated automatically (Figure 1.18).
Figure 1.18 Data binding between two controls
Deep data integration with controls enables powerful data visualization. In addition to traditional controls, WPF provides seamless access to documents, media, and graphics.
The Power of Integration
The visual system in WPF includes support for 2D vector graphics, raster images, text, animation, video, audio, and 3D graphics. All of these features are integrated into a single composition engine that builds on top of DirectX, allowing many features to be accelerated by hardware on modern video cards.
To start looking at this integration, let's create a rectangle. Instead of filling the rectangle with a solid color, we will create a gradient (blending from one color to another—in this case, from red to white to blue:
<Window ... > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <DockPanel> <WrapPanel DockPanel.Dock='Top'> <Button Background='{StaticResource bg}' Click='HowdyClicked'>Howdy!</Button> <Button Background='{StaticResource bg}'>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox Content='{Binding ElementName=_text1,Path=Text}' /> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> <Rectangle Margin='5'> <Rectangle.Fill> <LinearGradientBrush> <GradientStop Offset='0' Color='Red' /> <GradientStop Offset='.5' Color='White' /> <GradientStop Offset='1' Color='Blue' /> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> </DockPanel> </Window>
Figure 1.19 shows the result. Resizing the window shows that the rectangle changes size and the gradient rotates such that it starts and ends at the corners of the rectangle. Clearly, 2D graphics integrate with the layout engine.
Figure 1.19 Rectangle filled with a gradient
We can take this integration one step further, using a set of controls as the brush instead of filling the rectangle with a colored brush. In the following example, we will add a name to our wrap panel and use VisualBrush to fill the rectangle. VisualBrush takes a control and replicates the display of that control as the fill. Using the Viewport and TileMode properties, we can make the contents replicate multiple times:
<Window ... > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <DockPanel> <WrapPanel x:Name='panel' DockPanel.Dock='Top'> <Button Background='{StaticResource bg}' Click='HowdyClicked'>Howdy!</Button> <Button Background='{StaticResource bg}'>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox Content='{Binding ElementName=_text1,Path=Text}' /> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> <Rectangle Margin='5'> <Rectangle.Fill> <VisualBrush Visual='{Binding ElementName=panel}' Viewport='0,0,.5,.2' TileMode='Tile' /> </Rectangle.Fill> </Rectangle> </DockPanel> </Window>
Running this code shows that, if we edit the controls on the top, the display in the rectangle is updated (Figure 1.20). We can see that not only can we use 2D drawings with controls, but we can use controls themselves as 2D drawings. In fact, the implementations of all controls are described as a set of 2D drawings.
Figure 1.20 Using a visual brush to fill a rectangle
We can go even further with this integration. WPF provides basic 3D support as well. We can take the same visual brush and use it as a texture in a 3D drawing. Creating a 3D scene requires five things: a model (the shape), a material (what to cover the shape with), a camera (where to look from), a light (so we can see), and a viewport (someplace to render the scene). In Chapter 5 we'll look at 3D scenes in detail, but for now the important thing to notice is that, as the material of the model, we use the same visual brush as before:
<Window ... > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> </Window.Resources> <DockPanel> <WrapPanel x:Name='panel' DockPanel.Dock='Top'> <Button Background='{StaticResource bg}' Click='HowdyClicked'>Howdy!</Button> <Button Background='{StaticResource bg}'>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox Content='{Binding ElementName=_text1,Path=Text}' /> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> <Viewport3D> <Viewport3D.Camera> <PerspectiveCamera LookDirection='-.7,-.8,-1' Position='3.8,4,4' FieldOfView='17' UpDirection='0,1,0' /> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup> <PointLight Position='3.8,4,4' Color='White' Range='7' ConstantAttenuation='1.0' /> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D TextureCoordinates= '0,0 1,0 0,-1 1,-1 0,0 1,0 0,-1 0,0' Positions= '0,0,0 1,0,0 0,1,0 1,1,0 0,1,-1 1,1,-1 1,1,-1 1,0,-1' TriangleIndices='0,1,2 3,2,1 4,2,3 5,4,3 6,3,1 7,6,1' /> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial> <DiffuseMaterial.Brush> <VisualBrush Viewport='0,0,.5,.25' TileMode='Tile' Visual='{Binding ElementName=panel}' /> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> </GeometryModel3D> </Model3DGroup> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D> </DockPanel> </Window>
Figure 1.21 shows what this looks like. Just as when the shape was a 2D rectangle, changing the controls will be reflected on the 3D object.
Figure 1.21 Controls used as the material for a 3D shape
As the previous example shows, creating 3D scenes requires a lot of markup. I highly recommend using a 3D authoring tool if you intend to play with 3D.
Our last stop in looking at integration is animation. So far everything has been largely static. In the same way that 2D, 3D, text, and controls are integrated, everything in WPF supports animation intrinsically.
Animation in WPF allows us to vary a property value over time. To animate our 3D scene, we will start by adding a rotation transformation.
Rotation will allow us to spin our 3D model by adjusting the angle. We will then be able to animate the display by adjusting the angle property over time:
<!-- ...rest of scene... --> <GeometryModel3D> <GeometryModel3D.Transform> <RotateTransform3D CenterX='.5' CenterY='.5' CenterZ='-.5'> <RotateTransform3D.Rotation> <AxisAngleRotation3D x:Name='rotation' Axis='0,1,0' Angle='0' /> </RotateTransform3D.Rotation> </RotateTransform3D> </GeometryModel3D.Transform> <!-- ...rest of scene... -->
Now we can define our animation. There are a lot of details here, but the important thing is DoubleAnimation, which allows us to vary a double value over time. (ColorAnimation would allow us to animate a color value.) We are animating the angle of the rotation from –25 to 25. It will automatically reverse and take 2.5 seconds to complete each rotation.
<Window ...> <!-- ...rest of scene... --> <Window.Triggers> <EventTrigger RoutedEvent='FrameworkElement.Loaded'> <EventTrigger.Actions> <BeginStoryboard> <BeginStoryboard.Storyboard> <Storyboard> <DoubleAnimation From='-25' To='25' Storyboard.TargetName='rotation' Storyboard.TargetProperty='Angle' AutoReverse='True' Duration='0:0:2.5' RepeatBehavior='Forever' /> </Storyboard> </BeginStoryboard.Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Window.Triggers> <!-- ...rest of scene... -->
Running this code produces something like Figure 1.22, but animated. (I tried to get the publisher to include a laptop in every copy of the book so you could see the animation, but they decided it wouldn't be cost-effective.)
Figure 1.22 Adding rotation animation to our 3D scene
The integration of UI, documents, and media runs deep in WPF. We can give buttons texture with 3D, we can use a video as the fill for text—almost anything is possible. This flexibility is very powerful, but it can also lead to very unusable experiences. One of the tools that we can use to get a rich, but consistent, display is the WPF styling system.
Getting Some Style
Styles provide a mechanism for applying a set of properties to one or more controls. Because properties are used for almost all customization in WPF, we can customize almost every aspect of an application. Using styles, we can create consistent themes across applications.
To see how styles work, let's modify those two red buttons. First, instead of having each button refer to the resource, we can move the setting of the background to a style definition. By setting the key of the style to be the type Button, we ensure that that type will automatically be applied to all the buttons inside of this window:
<Window ... > <Window.Resources> <SolidColorBrush x:Key='bg' Color='Red' /> <Style x:Key='{x:Type Button}' TargetType='{x:Type Button}'> <Setter Property='Background' Value='{StaticResource bg}' /> </Style> </Window.Resources> <!-- ... rest of window ... --> <WrapPanel x:Name='panel' DockPanel.Dock='Top'> <Button Click='HowdyClicked'>Howdy!</Button> <Button>A second button</Button> <TextBox x:Name='_text1'>An editable text box</TextBox> <CheckBox Content='{Binding ElementName=_text1,Path=Text}' /> <Slider Width='75' Minimum='0' Maximum='100' Value='50' /> </WrapPanel> <!-- ... rest of window ... --> </Window>
Running this code will produce a result that looks indistinguishable from Figure 1.22. To make this more interesting, let's try customizing the Template property for the button. Most controls in WPF support templating, which means that the rendering of the control can be changed declaratively. Here we will replace the button's default appearance with a stylized ellipse.
ContentPresenter tells the template where to put the content of the button. Here we are using layout, controls, and 2D graphics to implement the display of a single button:
<Style x:Key='{x:Type Button}' TargetType='{x:Type Button}'> <Setter Property='Background' Value='{StaticResource bg}' /> <Setter Property='Template'> <Setter.Value> <ControlTemplate TargetType='{x:Type Button}'> <Grid> <Ellipse StrokeThickness='4'> <Ellipse.Stroke> <LinearGradientBrush> <GradientStop Offset='0' Color='White' /> <GradientStop Offset='1' Color='Black' /> </LinearGradientBrush> </Ellipse.Stroke> <Ellipse.Fill> <LinearGradientBrush> <GradientStop Offset='0' Color='Silver' /> <GradientStop Offset='1' Color='White' /> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Margin='10' HorizontalAlignment='Center' VerticalAlignment='Center' /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
Figure 1.23 (on page 40) shows what we get when we run this code. The buttons are still active; in fact, clicking the Howdy! button will still update the text box (remember, we wrote that code earlier in the tour).
Figure 1.23 Buttons with a custom template, provided by a style
We have now traveled through most of the areas of WPF, but we've only begun to scratch the surface of the concepts and features in this platform. Before we finish the introduction, we should talk about how to configure your computer to build and run all these wonderful programs that we're creating.