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

This chapter is from the book

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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