Vous êtes sur la page 1sur 105

Introduction to WPF

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

.NET Framework 4 - Windows Presentation Foundation

Introduction to WPF

Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both standalone and browser-hosted applications. An example is the Contoso Healthcare Sample Application that is shown in the following figure.

The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of modern graphics hardware. WPF extends the core with a comprehensive set of application-development features that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics, animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET Framework, so you can build applications that incorporate other elements of the .NET Framework class library. This overview is intended for newcomers and covers the key capabilities and concepts of WPF. Experienced WPF developers seeking a review of WPF may also find this overview useful.

Note
For new and updated WPF features in the .NET Framework 3.5, see What's New in WPF Version 4. This topic contains the following sections. Programming with WPF Markup and Code-Behind Applications Controls

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

Input and Commanding Layout Data Binding Graphics Animation Media Text and Typography Documents Customizing WPF Applications WPF Best Practices Summary Recommended Overviews and Samples Related Topics

Programming with WPF

WPF exists as a subset of .NET Framework types that are for the most part located in the System.Windows namespace. If you have previously built applications with .NET Framework using managed technologies like ASP.NET and Windows Forms, the fundamental WPF programming experience should be familiar; you instantiate classes, set properties, call methods, and handle events, all using your favorite .NET Framework programming language, such as C# or Visual Basic. To support some of the more powerful WPF capabilities and to simplify the programming experience, WPF includes additional programming constructs that enhance properties and events: dependency properties and routed events. For more information on dependency properties, see Dependency Properties Overview. For more information on routed events, see Routed Events Overview.

Markup and Code-Behind

WPF offers additional programming enhancements for Windows client application development. One obvious enhancement is the ability to develop an application using both markup and code-behind, an experience that ASP.NET developers should be familiar with. You generally use Extensible Application Markup Language (XAML) markup to implement the appearance of an application while using managed programming languages (code-behind) to implement its behavior. This separation of appearance and behavior has the following benefits: Development and maintenance costs are reduced because appearance-specific markup is not tightly coupled with behavior-specific code. Development is more efficient because designers can implement an application's appearance simultaneously with developers who are implementing the application's behavior. Multiple design tools can be used to implement and share XAML markup, to target the requirements of the application development contributors; Microsoft Expression Blend provides an experience that suits designers, while Visual Studio 2005 targets developers. Globalization and localization for WPF applications is greatly simplified (see WPF Globalization and Localization Overview). The following is a brief introduction to WPF markup and code-behind. For more information on this programming model, see XAML Overview (WPF) and Code-Behind and XAML in WPF.

Markup
http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

XAML is an XML-based markup language that is used to implement an application's appearance declaratively. It is typically used to create windows, dialog boxes, pages, and user controls, and to fill them with controls, shapes, and graphics. The following example uses XAML to implement the appearance of a window that contains a single button. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="Window with Button" Width="250" Height="100"> <!-- Add button to window --> <Button Name="button">Click Me!</Button> </Window>

Copy

Specifically, this XAML defines a window and a button by using the Window and Button elements, respectively. Each element is configured with attributes, such as the Window element's Title attribute to specify the window's title-bar text. At run time, WPF converts the elements and attributes that are defined in markup to instances of WPF classes. For example, the Window element is converted to an instance of the Window class whose Title property is the value of the Title attribute. The following figure shows the user interface (UI) that is defined by the XAML in the previous example.

For more information, see XAML Overview (WPF). Since XAML is XML-based, the UI that you compose with it is assembled in a hierarchy of nested elements known as an element tree. The element tree provides a logical and intuitive way to create and manage UIs. For more information, see Trees in WPF.

Code-Behind
The main behavior of an application is to implement the functionality that responds to user interactions, including handling events (for example, clicking a menu, tool bar, or button) and calling business logic and data access logic in response. In WPF, this behavior is generally implemented in code that is associated with markup. This type of code is known as code-behind. The following example shows the code-behind and updated markup from the previous example. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.AWindow" Title="Window with Button" Width="250" Height="100"> <!-- Add button to window --> <Button Name="button" Click="button_Click">Click Me!</Button> </Window>

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

VB

C#

C++

F#

JScript

Copy

Namespace SDKSample Partial Public Class AWindow Inherits System.Windows.Window Public Sub New() ' InitializeComponent call is required to merge the UI ' that is defined in markup with this class, including ' setting properties and registering event handlers InitializeComponent() End Sub Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) ' Show message box when button is clicked MessageBox.Show("Hello, Windows Presentation Foundation!") End Sub End Class End Namespace

In this example, the code-behind implements a class that derives from the Window class. The x:Class attribute is used to associate the markup with the code-behind class. InitializeComponent is called from the code-behind class's constructor to merge the UI that is defined in markup with the code-behind class. (InitializeComponent is generated for you when your application is built, which is why you don't need to implement it manually.) The combination of x:Class and InitializeComponent ensure that your implementation is correctly initialized whenever it is created. The code-behind class also implements an event handler for the button's Click event. When the button is clicked, the event handler shows a message box by calling the MessageBox.Show method. The following figure shows the result when the button is clicked.

For more information, see Code-Behind and XAML in WPF.

Applications
http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

.NET Framework, System.Windows, and markup and code-behind, constitute the foundation of the WPF application development experience. Additionally, WPF has comprehensive features for creating user experiences with rich content. To package this content and deliver it to users as "applications," WPF provides types and services that are collectively known as the application model. The application model supports the development of both standalone and browser-hosted applications.

Standalone Applications
For standalone applications, you can use the Window class to create windows and dialog boxes that are accessed from menu bars and tool bars. The following figure shows a standalone application with a main window and a dialog box.

Additionally, you can use the following WPF dialog boxes: MessageBox, OpenFileDialog, SaveFileDialog, and PrintDialog. For more information, see WPF Windows Overview.

Browser-Hosted Applications
For browser-hosted applications, known as XAML browser applications (XBAPs), you can create pages (Page) and page functions (PageFunction(Of T)) that you can navigate between using hyperlinks (Hyperlink classes). The following figure shows a page in an XBAP that is hosted in Internet Explorer 7.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

WPF applications can be hosted in both Microsoft Internet Explorer 6 and Internet Explorer 7. WPF offers the two following options for alternative navigation hosts: Frame, to host islands of navigable content in either pages or windows. NavigationWindow, to host navigable content in an entire window. For more information, see Navigation Overview.

The Application Class


Both XBAPs and standalone applications are often complex enough to require additional application-scoped services, including startup and lifetime management, shared properties, and shared resources. The Application class encapsulates these services and more, and it can be implemented by just using XAML, as shown in the following example. XAML
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="MainWindow.xaml" />

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

This markup is the application definition for a standalone application, and instructs WPF to create an Application object that automatically opens MainWindow when the application is started. A key concept to understand about Application is that it provides a common platform of support for both standalone and browser-hosted applications. For example, the preceding XAML could be used by a browser-hosted application to automatically navigate to a page when an XBAP is started, as shown in the following example. XAML
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartupUri="HomePage.xaml" />

Copy

For more information, see Application Management Overview.

Security
Because XBAPs are hosted in a browser, security is important. In particular, a partial-trust security sandbox is used by XBAPs to enforce restrictions that are less than or equal to the restrictions imposed on HTML-based applications. Furthermore, each HTML feature that is safe to run from XBAPs in partial trust has been tested using a comprehensive security process, detailed in WPF Security Strategy - Security Engineering. Still, a majority of WPF features can be safely executed from XBAPs, as described in WPF Partial Trust Security.

Controls

The user experiences that are delivered by the application model are constructed controls. In WPF, "control" is an umbrella term that applies to a category of WPF classes that are hosted in either a window or a page, have a user interface (UI), and implement some behavior. For more information, see Controls.

WPF Controls by Function


The built-in WPF controls are listed here. Buttons: Button and RepeatButton. Data Display: DataGrid, ListView,and TreeView. Date Display and Selection: Calendar and DatePicker. Dialog Boxes: OpenFileDialog, PrintDialog, and SaveFileDialog. Digital Ink: InkCanvas and InkPresenter. Documents: DocumentViewer, FlowDocumentPageViewer, FlowDocumentReader, FlowDocumentScrollViewer, and StickyNoteControl. Input: TextBox, RichTextBox, and PasswordBox.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

Layout: Border, BulletDecorator, Canvas, DockPanel, Expander, Grid, GridView, GridSplitter, GroupBox, Panel, ResizeGrip, Separator, ScrollBar, ScrollViewer, StackPanel, Thumb, Viewbox, VirtualizingStackPanel, Window, and WrapPanel. Media: Image, MediaElement, and SoundPlayerAction. Menus: ContextMenu, Menu, and ToolBar. Navigation: Frame, Hyperlink, Page, NavigationWindow, and TabControl. Selection: CheckBox, ComboBox, ListBox, RadioButton, and Slider. User Information: AccessText, Label, Popup, ProgressBar, StatusBar, TextBlock, and ToolTip.

Input and Commanding

Controls most often detect and respond to user input. The WPF input system uses both direct and routed events to support text input, focus management, and mouse positioning. For more information, see Input Overview. Applications often have complex input requirements. WPF provides a command system that separates user input actions from the code that responds to those actions. For more information, see Commanding Overview.

Layout

When you create a UI, you arrange your controls by location and size to form a layout. A key requirement of any layout is to adapt to changes in window size and display settings. Rather than forcing you to write the code to adapt a layout in these circumstances, WPF provides a first-class, extensible layout system for you. The cornerstone of the layout system is relative positioning, which increases the ability to adapt to changing window and display conditions. In addition, the layout system manages the negotiation between controls to determine the layout. The negotiation is a two-step process: first, a control tells its parent what location and size it requires; second, the parent tells the control what space it can have. The layout system is exposed to child controls through base WPF classes. For common layouts such as grids, stacking, and docking, WPF includes several layout controls: Canvas: Child controls provide their own layout. DockPanel: Child controls are aligned to the edges of the panel. Grid: Child controls are positioned by rows and columns. StackPanel: Child controls are stacked either vertically or horizontally. VirtualizingStackPanel: Child controls are virtualized and arranged on a single line that is either horizontally or vertically oriented. WrapPanel: Child controls are positioned in left-to-right order and wrapped to the next line when there are more controls on the current line than space allows. The following example uses a DockPanel to lay out several TextBox controls.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.LayoutWindow" Title="Layout with the DockPanel" Height="143" Width="319"> <!--DockPanel to layout four text boxes--> <DockPanel> <TextBox DockPanel.Dock="Top">Dock = "Top"</TextBox> <TextBox DockPanel.Dock="Bottom">Dock = "Bottom"</TextBox> <TextBox DockPanel.Dock="Left">Dock = "Left"</TextBox> <TextBox Background="White">This TextBox "fills" the remaining space.</TextBox> </DockPanel> </Window>

Copy

The DockPanel allows the child TextBox controls to tell it how to arrange them. To do this, the DockPanel implements a Dock property that is exposed to the child controls to allow each of them to specify a dock style.

Note
A property that is implemented by a parent control for use by child controls is a WPF construct called an attached property (see Attached Properties Overview). The following figure shows the result of the XAML markup in the preceding example.

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

Data Binding

Most applications are created to provide users with the means to view and edit data. For WPF applications, the work of storing and accessing data is already provided for by technologies such as Microsoft SQL Server and ADO.NET. After the data is accessed and loaded into an application's managed objects, the hard work for WPF applications begins. Essentially, this involves two things: 1. Copying the data from the managed objects into controls, where the data can be displayed and edited. 2. Ensuring that changes made to data by using controls are copied back to the managed objects. To simplify application development, WPF provides a data binding engine to automatically perform these steps. The core unit of the data binding engine is the Binding class, whose job is to bind a control (the binding target) to a data object (the binding source). This relationship is illustrated by the following figure.
http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

The following example demonstrates how to bind a TextBox to an instance of a custom Person object. The Person implementation is shown in the following code. VB C# C++ F# JScript

Copy

Namespace SDKSample Class Person Private _name As String = "No Name" Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property End Class End Namespace

The following markup binds the TextBox to an instance of a custom Person object. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.DataBindingWindow">

Copy

...

<!-- Bind the TextBox to the data source (TextBox.Text to Person.Name) --> <TextBox Name="personNameTextBox" Text="{Binding Path=Name}" />

...

</Window>

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

VB

C#

C++

F#

JScript

Copy

Imports System.Windows ' Window Namespace SDKSample Partial Public Class DataBindingWindow Inherits Window Public Sub New() InitializeComponent() ' Create Person data source Dim person As Person = New Person() ' Make data source available for binding Me.DataContext = person End Sub End Class End Namespace

In this example, the Person class is instantiated in code-behind and is set as the data context for the DataBindingWindow. In markup, the Text property of the TextBox is bound to the Person.Name property (using the "{Binding ... }" XAML syntax). This XAML tells WPF to bind the TextBox control to the Person object that is stored in the DataContext property of the window. The WPF data binding engine provides additional support that includes validation, sorting, filtering, and grouping. Furthermore, data binding supports the use of data templates to create custom UI for bound data when the UI displayed by the standard WPF controls is not appropriate. For more information, see Data Binding Overview. For an introductory sample, see Data Binding Demo.

Graphics

WPF introduces an extensive, scalable, and flexible set of graphics features that have the following benefits: Resolution-independent and device-independent graphics. The basic unit of measurement in the WPF graphics system is the device independent pixel, which is 1/96th of an inch, regardless of actual screen resolution, and provides the foundation for resolution-independent and device-independent rendering. Each device-independent pixel automatically scales to match the dots-per-inch (dpi) setting of the system it renders on. Improved precision. The WPF coordinate system is measured with double-precision floating-point numbers rather than single-precision. Transformations and opacity values are also expressed as double-precision. WPF also supports a wide color gamut (scRGB) and provides integrated support for managing inputs from different color spaces. Advanced graphics and animation support. WPF simplifies graphics programming by managing animation scenes for you; there is no need to worry about scene processing, rendering loops, and bilinear interpolation. Additionally, WPF provides hit-testing support and full alpha-compositing support. Hardware acceleration. The WPF graphics system takes advantage of graphics hardware to minimize CPU usage.

2-D Shapes

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

WPF provides a library of common vector-drawn 2-D shapes, such as the rectangles and ellipses that are shown in the following illustration.

An interesting capability of shapes is that they are not just for display; shapes implement many of the features that you expect from controls, including keyboard and mouse input. The following example shows the MouseUp event of an Ellipse being handled. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.EllipseEventHandlingWindow" Title="Click the Ellipse"> <Ellipse Name="clickableEllipse" Fill="Blue" MouseUp="clickableEllipse_MouseUp" /> </Window>

Copy

VB

C#

C++

F#

JScript

Copy

Imports System.Windows ' Window, MessageBox Imports System.Windows.Input ' MouseButtonEventArgs Namespace SDKSample Public Class EllipseEventHandlingWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub clickableEllipse_MouseUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs) MessageBox.Show("You clicked the ellipse!") End Sub End Class End Namespace

The following figure shows what is produced by the preceding code.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

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

2-D Geometries
The 2-D shapes provided by WPF cover the standard set of basic shapes. However, you may need to create custom shapes to facilitate the design of a customized UI. For this purpose, WPF provides geometries. The following figure demonstrates the use of geometries to create a custom shape that can be drawn directly, used as a brush, or used to clip other shapes and controls. Path objects can be used to draw closed or open shapes, multiple shapes, and even curved shapes. Geometry objects can be used for clipping, hit-testing, and rendering 2-D graphic data.

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

2-D Effects
A subset of WPF 2-D capabilities includes visual effects, such as gradients, bitmaps, drawings, painting with videos, rotation, scaling, and skewing. These are all achieved with brushes; the following figure shows some examples.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

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

3-D Rendering
WPF also includes 3-D rendering capabilities that integrate with 2-D graphics to allow the creation of more exciting and interesting UIs. For example, the following figure shows 2-D images rendered onto 3-D shapes.

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

Animation

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

WPF animation support lets you make controls grow, shake, spin, and fade, to create interesting page transitions, and more. You can animate most WPF classes, even custom classes. The following figure shows a simple animation in action.

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

Media

One way to convey rich content is through the use of audiovisual media. WPF provides special support for images, video, and audio.

Images
Images are common to most applications, and WPF provides several ways to use them. The following figure shows a UI with a list box that contains thumbnail images. When a thumbnail is selected, the image is shown full-size.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

For more information, see Imaging Overview.

Video and Audio


The MediaElement control is capable of playing both video and audio, and it is flexible enough to be the basis for a custom media player. The following XAML markup implements a media player. XAML
<MediaElement Name="myMediaElement" Source="media/wpf.wmv" LoadedBehavior="Manual" Width="350" Height="250" />

Copy

The window in the following figure shows the MediaElement control in action.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

For more information, see Graphics and Multimedia.

Text and Typography

To facilitate high-quality text rendering, WPF offers the following features: OpenType font support. ClearType enhancements. High performance that takes advantage of hardware acceleration. Integration of text with media, graphics, and animation. International font support and fallback mechanisms. As a demonstration of text integration with graphics, the following figure shows the application of text decorations.

For more information, see Typography in WPF.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

Documents

WPF has native support for working with three types of documents: flow documents, fixed documents, and XML Paper Specification (XPS) documents. WPF also provides the services to create, view, manage, annotate, package, and print documents.

Flow Documents
Flow documents are designed to optimize viewing and readability by dynamically adjusting and reflowing content when window size and display settings change. The following XAML markup shows the definition of a FlowDocument. XAML
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Paragraph FontSize="18" FontWeight="Bold">Flow Document</Paragraph> <Paragraph> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure. </Paragraph>

Copy

...

</FlowDocument>

The following example demonstrates how to load a flow document into a FlowDocumentReader for viewing, searching, and printing. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.FlowDocumentReaderWindow" Title="Flow Document Reader"> <FlowDocumentReader Name="flowDocumentReader" /> </Window>

Copy

VB

C#

C++

F#

JScript

Copy

Imports Imports Imports Imports

System.Windows 'Window System.Windows.Documents 'FlowDocument System.IO 'FileStream, FileMode System.Windows.Markup 'XamlReader

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
Namespace SDKSample Public Class FlowDocumentReaderWindow Inherits Window Public Sub New() Me.InitializeComponent() Using stream1 As FileStream = New FileStream("AFlowDocument.xaml", _ FileMode.Open, FileAccess.Read) Dim document1 As FlowDocument = _ TryCast(XamlReader.Load(stream1), FlowDocument) Me.flowDocumentReader.Document = document1 End Using End Sub End Class End Namespace

The following example shows the result.

For more information, see Flow Document Overview.

Fixed Documents
Fixed documents are intended for applications that require a precise "what you see is what you get" (WYSIWYG) presentation, particularly with respect to printing. Typical uses for fixed documents include desktop publishing, word processing, and form layout, where adherence to the original page design is critical. Fixed documents maintain the precise arrangement of their content in a device-independent manner. For example, a fixed document that is displayed on a 96 dots-per-inch (dpi) display appears the same as when it is printed to either a 600 dpi laser printer or a 4800 dpi photo typesetter. The layout remains the same in all cases, although the document's quality varies depending on the capabilities of each device. For more information, see Documents in WPF.

XPS Documents
XML Paper Specification (XPS) documents build on WPF's fixed documents. XPS documents are described with an XML-based schema that is essentially a paginated representation of electronic paper. XPS is an open, cross-platform document format that is designed to facilitate the creation, sharing, printing, and archiving of paginated documents. Important features of the XPS technology include the following: Packaging of XPS documents as ZipPackage files that conform to the Open Packaging Conventions (OPC). Hosting in both standalone and browser-based applications. Manual generation and manipulation of XPS documents from WPF applications.
http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

High-fidelity rendering by targeting maximum output device quality. Windows Vista print spooling. Direct routing of documents to XPS-compatible printers. UI integration with DocumentViewer. The following figure shows an XPS document that is displayed by a DocumentViewer.

DocumentViewer also allows users to change the view, search, and print XPS documents. For more information, see Documents in WPF.

Annotations
Annotations are notes or comments that are added to documents to flag information or to highlight items of interest for later reference. Although writing notes on printed documents is easy, the ability to "write" notes on electronic documents is often limited or unavailable. In WPF, however, an annotations system is provided to support sticky notes and highlights. Additionally, these annotations can be applied to documents hosted in the DocumentViewer control, as shown in the following figure.

For more information, see Annotations Overview.

Packaging
The WPF System.IO.Packaging APIs allow your applications to organize data, content, and resources into single, portable, easy-todistribute, and easy-to-access ZIP documents. Digital signatures can be included to authenticate items that are contained in a

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

package and to verify that the signed item was not tampered with or modified. You can also encrypt packages by using rights management in order to restrict access to protected information. For more information, see Documents in WPF.

Printing
The .NET Framework includes a printing subsystem that WPF augments with support for enhanced print system control. Printing enhancements include the following: Real-time installation of remote print servers and queues. Dynamic discovery of printer capabilities. Dynamic setting of printer options. Print job rerouting and reprioritizing. XPS documents also have a key performance enhancement. The existing Microsoft Windows Graphics Device Interface (GDI) print path typically requires two conversions: The first conversion of a document into a print processor format, such as Enhanced Metafile (EMF). A second conversion into the page description language of the printer, such as Printer Control Language (PCL) or PostScript. However, XPS documents avoid these conversions because one component of the XPS file format is a print processor language and a page description language. This support helps to reduce both spool file size and networked printer loads. For more information, see Printing Overview.

Customizing WPF Applications

Up to this point, you've seen the core WPF building blocks for developing applications. You use the application model to host and deliver application content, which consists mainly of controls. To simplify the arrangement of controls in a UI, and to ensure the arrangement is maintained in the face of changes to window size and display settings, you use the WPF layout system. Because most applications allow users to interact with data, you use data binding to reduce the work of integrating your UI with data. To enhance the visual appearance of your application, you use the comprehensive range of graphics, animation, and media support provided by WPF. Finally, if your application operates over text and documents, you can use the WPF text, typography, document, annotation, packaging, and printing capabilities. Often, though, the basics are not enough for creating and managing a truly distinct and visually stunning user experience. The standard WPF controls may not integrate with the desired appearance of your application. Data may not be displayed in the most effective way. Your application's overall user experience may not be suited to the default look and feel of Windows themes. In many ways, a presentation technology needs visual extensibility as much as any other kind of extensibility. For this reason, WPF provides a variety of mechanisms for creating unique user experiences, including a rich content model for controls, triggers, control and data templates, styles, UI resources, and themes and skins.

Content Model
The main purpose of a majority of the WPF controls is to display content. In WPF, the type and number of items that can constitute the content of a control is referred to as the control's content model. Some controls can contain a single item and type of content; for example, the content of a TextBox is a string value that is assigned to the Text property. The following example sets the content of a TextBox.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.TextBoxContentWindow" Title="TextBox Content">

Copy

...

<TextBox Text="This is the content of a TextBox." />

...

</Window>

The following figure shows the result.

Other controls, however, can contain multiple items of different types of content; the content of a Button, specified by the Content property, can contain a variety of items including layout controls, text, images, and shapes. The following example shows a Button with content that includes a DockPanel, a Label, a Border, and a MediaElement. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.ButtonContentWindow" Title="Button Content">

Copy

...

<Button Margin="20"> <!-- Button Content --> <DockPanel Width="200" Height="180"> <Label DockPanel.Dock="Top" HorizontalAlignment="Center">Click Me!</Label> <Border Background="Black" BorderBrush="Yellow" BorderThickness="2" CornerRadius="2" Margin="5"> <MediaElement Source="media/wpf.wmv" Stretch="Fill" /> </Border> </DockPanel> </Button>

...

</Window>

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

The following figure shows the content of this button.

For more information on the kinds of content that is supported by various controls, see WPF Content Model.

Triggers
Although the main purpose of XAML markup is to implement an application's appearance, you can also use XAML to implement some aspects of an application's behavior. One example is the use of triggers to change an application's appearance based on user interactions. For more information, see "Triggers" in Styling and Templating.

Control Templates
The default UIs for WPF controls are typically constructed from other controls and shapes. For example, a Button is composed of both ButtonChrome and ContentPresenter controls. The ButtonChrome provides the standard button appearance, while the ContentPresenter displays the button's content, as specified by the Content property. Sometimes the default appearance of a control may be incongruent with the overall appearance of an application. In this case, you can use a ControlTemplate to change the appearance of the control's UI without changing its content and behavior. For example, the following example shows how to change the appearance of a Button by using a ControlTemplate. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.ControlTemplateButtonWindow" Title="Button with Control Template" Height="158" Width="290"> <!-- Button using an ellipse --> <Button Content="Click Me!" Click="button_Click"> <Button.Template> <ControlTemplate TargetType="{x:Type Button}"> <Grid Margin="5"> <Ellipse Stroke="DarkBlue" StrokeThickness="2"> <Ellipse.Fill> <RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5"> <GradientStop Color="Azure" Offset="0.1" /> <GradientStop Color="CornflowerBlue" Offset="1.1" /> </RadialGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Name="content" HorizontalAlignment="Center"

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
VerticalAlignment="Center"/> </Grid> </ControlTemplate> </Button.Template> </Button> </Window>

VB

C#

C++

F#

JScript

Copy

Imports System.Windows ' Window, RoutedEventArgs, MessageBox Namespace SDKSample Public Class ControlTemplateButtonWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) MessageBox.Show("Hello, Windows Presentation Foundation!") End Sub End Class End Namespace

In this example, the default button UI has been replaced with an Ellipse that has a dark blue border and is filled using a RadialGradientBrush. The ContentPresenter control displays the content of the Button, "Click Me!" When the Button is clicked, the Click event is still raised as part of the Button control's default behavior. The result is shown in the following figure.

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

Data Templates
Whereas a control template lets you specify the appearance of a control, a data template lets you specify the appearance of a control's content. Data templates are frequently used to enhance how bound data is displayed. The following figure shows the

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

default appearance for a ListBox that is bound to a collection of Task objects, where each task has a name, description, and priority.

The default appearance is what you would expect from a ListBox. However, the default appearance of each task contains only the task name. To show the task name, description, and priority, the default appearance of the ListBox control's bound list items must be changed by using a DataTemplate. The following XAML defines such a DataTemplate, which is applied to each task by using the ItemTemplate attribute. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.DataTemplateWindow" Title="With a Data Template">

Copy

...

<Window.Resources> <!-- Data Template (applied to each bound task item in the task collection) --> <DataTemplate x:Key="myTaskTemplate"> <Border Name="border" BorderBrush="DarkSlateBlue" BorderThickness="2" CornerRadius="2" Padding="5" Margin="5"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Padding="0,0,5,0" Text="Task Name:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=TaskName}"/> <TextBlock Grid.Row="1" Grid.Column="0" Padding="0,0,5,0" Text="Description:"/> <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Description}"/> <TextBlock Grid.Row="2" Grid.Column="0" Padding="0,0,5,0" Text="Priority:"/> <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Priority}"/> </Grid> </Border> </DataTemplate> </Window.Resources>

...

<!-- UI -->

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
<DockPanel> <!-- Title --> <Label DockPanel.Dock="Top" FontSize="18" Margin="5" Content="My Task List:"/> <!-- Data template is specified by the ItemTemplate attribute --> <ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource myTaskTemplate}" HorizontalContentAlignment="Stretch" IsSynchronizedWithCurrentItem="True" Margin="5,0,5,5" /> </DockPanel>

...

</Window>

The following figure shows the effect of this code.

Note that the ListBox has retained its behavior and overall appearance; only the appearance of the content being displayed by the list box has changed. For more information, see Data Templating Overview. For an introductory sample, see Introduction to Data Templating Sample.

Styles
Styles enable developers and designers to standardize on a particular appearance for their product. WPF provides a strong style model, the foundation of which is the Style element. The following example creates a style that sets the background color for every Button on a window to Orange. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.StyleWindow" Title="Styles">

Copy

...

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
<!-- Style that will be applied to all buttons --> <Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="Orange" /> <Setter Property="BorderBrush" Value="Crimson" /> <Setter Property="FontSize" Value="20" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Margin" Value="5" /> </Style>

...

<!-- This button will have the style applied to it --> <Button>Click Me!</Button> <!-- This labe will not have the style applied to it --> <Label>Don't Click Me!</Label> <!-- This button will have the style applied to it --> <Button>Click Me!</Button>

...

</Window>

Because this style targets all Button controls, the style is automatically applied to all the buttons in the window, as shown in the following figure.

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

Resources
Controls in an application should share the same appearance, which can include anything from fonts and background colors to control templates, data templates, and styles. You can use WPF's support for user interface (UI) resources to encapsulate these resources in a single location for reuse. The following example defines a common background color that is shared by a Button and a Label. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.ResourcesWindow" Title="Resources Window"> <!-- Define window-scoped background color resource -->

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
<Window.Resources> <SolidColorBrush x:Key="defaultBackground" Color="Red" /> </Window.Resources>

...

<!-- Button background is defined by window-scoped resource --> <Button Background="{StaticResource defaultBackground}">One Button</Button> <!-- Label background is defined by window-scoped resource --> <Label Background="{StaticResource defaultBackground}">One Label</Label>

...

</Window>

This example implements a background color resource by using the Window.Resources property element. This resource is available to all children of the Window. There are a variety of resource scopes, including the following, listed in the order in which they are resolved: 1. An individual control (using the inherited FrameworkElement.Resources property). 2. A Window or a Page (also using the inherited FrameworkElement.Resources property). 3. An Application (using the Application.Resources property). The variety of scopes gives you flexibility with respect to the way in which you define and share your resources. As an alternative to directly associating your resources with a particular scope, you can package one or more resources by using a separate ResourceDictionary that can be referenced in other parts of an application. For example, the following example defines a default background color in a resource dictionary. XAML
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Define background color resource --> <SolidColorBrush x:Key="defaultBackground" Color="Red" /> <!-- Define other resources -->

Copy

...

</ResourceDictionary>

The following example references the resource dictionary defined in the previous example so that it is shared across an application. XAML

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.App"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="BackgroundColorResources.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>

...

</Application>

Resources and resource dictionaries are the foundation of WPF support for themes and skins. For more information, see Resources Overview.

Themes and Skins


From a visual perspective, a theme defines the global appearance of Windows and the applications that run within it. Windows comes with several themes. For example, Microsoft Windows XP comes with both the Windows XP and Windows Classic themes, while Windows Vista comes with the Windows Vista and Windows Classic themes. The appearance that is defined by a theme defines the default appearance for a WPF application. WPF, however, does not integrate directly with Windows themes. Because the appearance of WPF is defined by templates, WPF includes one template for each of the well-known Windows themes, including Aero (Windows Vista), Classic (Microsoft Windows 2000), Luna (Microsoft Windows XP), and Royale (Microsoft Windows XP Media Center Edition 2005). These themes are packaged as resource dictionaries that are resolved if resources are not found in an application. Many applications rely on these themes to define their visual appearance; remaining consistent with Windows appearance helps users become familiar with more applications more easily. On the other hand, the user experience for some applications does not necessarily come from the standard themes. For example, Microsoft Windows Media Player operates over audio and video data and benefits from a different style of user experience. Such UIs tend to provide customized, application-specific themes. These are known as skins, and applications that are skinned often provide hooks by which users can customize various aspects of the skin. Microsoft Windows Media Player has several prefabricated skins as well as a host of third-party skins. Both themes and skins in WPF are most easily defined using resource dictionaries. The following example shows sample skin definitions. XAML
<!-- Blue Skin --> <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SDKSample"> <Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="Blue" /> </Style>

Copy

...

</ResourceDictionary>

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

XAML
<!-- Yellow Skin --> <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SDKSample"> <Style TargetType="{x:Type Button}"> <Setter Property="Background" Value="Yellow" /> </Style>

Copy

...

</ResourceDictionary>

For more information, see "Shared Resources and Themes" in Styling and Templating.

Custom Controls
Although WPF provides a host of customization support, you may encounter situations where existing WPF controls do not meet the needs of either your application or its users. This can occur when: The UI that you require cannot be created by customizing the look and feel of existing WPF implementations. The behavior that you require is not supported (or not easily supported) by existing WPF implementations. At this point, however, you can take advantage of one of three WPF models to create a new control. Each model targets a specific scenario and requires your custom control to derive from a particular WPF base class. The three models are listed here: User Control Model. A custom control derives from UserControl and is composed of one or more other controls. Control Model. A custom control derives from Control and is used to build implementations that separate their behavior from their appearance using templates, much like the majority of WPF controls. Deriving from Control allows you more freedom for creating a custom UI than user controls, but it may require more effort. Framework Element Model. A custom control derives from FrameworkElement when its appearance is defined by custom rendering logic (not templates). The following example shows a custom numeric up/down control that derives from UserControl. XAML
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.NumericUpDown"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/>

Copy

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
<ColumnDefinition/> </Grid.ColumnDefinitions> <!-- Value text box --> <Border BorderThickness="1" BorderBrush="Gray" Margin="2" Grid.RowSpan="2" VerticalAlignment="Center" HorizontalAlignment="Stretch"> <TextBlock Name="valueText" Width="60" TextAlignment="Right" Padding="5"/> </Border> <!-- Up/Down buttons --> <RepeatButton Name="upButton" Click="upButton_Click" Grid.Column="1" Grid.Row="0">Up</RepeatButton> <RepeatButton Name="downButton" Click="downButton_Click" Grid.Column="1" Grid.Row="1">Down</RepeatButton> </Grid> </UserControl>

VB

C#

C++

F#

JScript

Copy

imports System 'EventArgs imports System.Windows 'DependencyObject, DependencyPropertyChangedEventArgs, ' FrameworkPropertyMetadata, PropertyChangedCallback, ' RoutedPropertyChangedEventArgs imports System.Windows.Controls 'UserControl Namespace SDKSample ' Interaction logic for NumericUpDown.xaml Partial Public Class NumericUpDown Inherits System.Windows.Controls.UserControl 'NumericUpDown user control implementation

...

End Class End Namespace

The next example illustrates the XAML that is required to incorporate the user control into a Window. XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.UserControlWindow" xmlns:local="clr-namespace:SDKSample" Title="User Control Window">

Copy

...

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

<!-- Numeric Up/Down user control --> <local:NumericUpDown />

...

</Window>

The following figure shows the NumericUpDown control hosted in a Window.

For more information on custom controls, see Control Authoring Overview.

WPF Best Practices

As with any development platform, WPF can be used in a variety of ways to achieve the desired result. As a way of ensuring that your WPF applications provide the required user experience and meet the demands of the audience in general, there are recommended best practices for accessibility, globalization and localization, and performance. See the following for more information: Accessibility Best Practices WPF Globalization and Localization Overview Optimizing WPF Application Performance Security (WPF)

Summary

WPF is a comprehensive presentation technology for building a wide variety of visually stunning client applications. This introduction has provided a look at the key features of WPF. The next step is to build WPF applications! As you build them, you can come back to this introduction for a refresher on the key features and to find references to more detailed coverage of the features covered in this introduction.

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF

Recommended Overviews and Samples

The following overviews and samples are mentioned in this introduction.

Overviews

Accessibility Best Practices Application Management Overview Commanding Overview Controls Data Binding Overview Dependency Properties Overview Documents in WPF

Input Overview Layout System Navigation Overview Printing Overview Resources Overview Routed Events Overview Styling and Templating Typography in WPF Security (WPF) WPF Windows Overview WPF Content Model WPF Globalization and Localization Overview Graphics and Multimedia

Samples

3-D Solids Sample Animation Example Gallery Brushes Sample Data Binding Demo Geometries Sample

Introduction to Data Templating Sample Introduction to Styling and Templating Sample Shape Elements Sample Styling with ControlTemplates Sample WPF Layout Gallery Sample

See Also

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

Introduction to WPF
Concepts

Walkthrough: Getting Started with WPF WPF Community Feedback

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/aa970268.aspx[6/18/2010 12:13:09 PM]

WPF Architecture

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

.NET Framework 4 - Windows Presentation Foundation

WPF Architecture

This topic provides a guided tour of the Windows Presentation Foundation (WPF) class hierarchy. It covers most of the major subsystems of WPF, and describes how they interact. It also details some of the choices made by the architects of WPF. This topic contains the following sections. System.Object System.Threading.DispatcherObject System.Windows.DependencyObject System.Windows.Media.Visual System.Windows.UIElement System.Windows.FrameworkElement System.Windows.Controls.Control Summary Related Topics

System.Object

The primary WPF programming model is exposed through managed code. Early in the design phase of WPF there were a number of debates about where the line should be drawn between the managed components of the system and the unmanaged ones. The CLR provides a number of features that make development more productive and robust (including memory management, error handling, common type system, etc.) but they come at a cost. The major components of WPF are illustrated in the figure below. The red sections of the diagram (PresentationFramework, PresentationCore, and milcore) are the major code portions of WPF. Of these, only one is an unmanaged component milcore. Milcore is written in unmanaged code in order to enable tight integration with DirectX. All display in WPF is done through the DirectX engine, allowing for efficient hardware and software rendering. WPF also required fine control over memory and execution. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance.

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

Communication between the managed and unmanaged portions of WPF is discussed later in this topic. The remainder of the managed programming model is described below.

System.Threading.DispatcherObject

Most objects in WPF derive from DispatcherObject, which provides the basic constructs for dealing with concurrency and threading. WPF is based on a messaging system implemented by the dispatcher. This works much like the familiar Win32 message pump; in fact, the WPF dispatcher uses User32 messages for performing cross thread calls. There are really two core concepts to understand when discussing concurrency in WPF the dispatcher and thread affinity. During the design phase of WPF, the goal was to move to a single thread of execution, but a non-thread "affinitized" model. Thread affinity happens when a component uses the identity of the executing thread to store some type of state. The most common form of this is to use the thread local store (TLS) to store state. Thread affinity requires that each logical thread of execution be owned by only one physical thread in the operating system, which can become memory intensive. In the end, WPFs threading model was kept in sync with the existing User32 threading model of single threaded execution with thread affinity. The primary reason for this was interoperability systems like OLE 2.0, the clipboard, and Internet Explorer all require single thread affinity (STA) execution. Given that you have objects with STA threading, you need a way to communicate between threads, and validate that you are on the correct thread. Herein lies the role of the dispatcher. The dispatcher is a basic message dispatching system, with multiple prioritized queues. Examples of messages include raw input notifications (mouse moved), framework functions (layout), or user commands (execute this method). By deriving from DispatcherObject, you create a CLR object that has STA behavior, and will be given a pointer to a dispatcher at creation time.

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

System.Windows.DependencyObject

One of the primary architectural philosophies used in building WPF was a preference for properties over methods or events. Properties are declarative and allow you to more easily specify intent instead of action. This also supported a model driven, or data driven, system for displaying user interface content. This philosophy had the intended effect of creating more properties that you could bind to, in order to better control the behavior of an application. In order to have more of the system driven by properties, a richer property system than what the CLR provides was needed. A simple example of this richness is change notifications. In order to enable two way binding, you need both sides of the bind to support change notification. In order to have behavior tied to property values, you need to be notified when the property value changes. The Microsoft .NET Framework has an interface, INotifyPropertyChange, which allows an object to publish change notifications, however it is optional. WPF provides a richer property system, derived from the DependencyObject type. The property system is truly a "dependency" property system in that it tracks dependencies between property expressions and automatically revalidates property values when dependencies change. For example, if you have a property that inherits (like FontSize), the system is automatically updated if the property changes on a parent of an element that inherits the value. The foundation of the WPF property system is the concept of a property expression. In this first release of WPF, the property expression system is closed, and the expressions are all provided as part of the framework. Expressions are why the property system doesnt have data binding, styling, or inheritance hard coded, but rather provided by later layers within the framework. The property system also provides for sparse storage of property values. Because objects can have dozens (if not hundreds) of properties, and most of the values are in their default state (inherited, set by styles, etc.), not every instance of an object needs to have the full weight of every property defined on it. The final new feature of the property system is the notion of attached properties. WPF elements are built on the principle of composition and component reuse. It is often the case that some containing element (like a Grid layout element) needs additional data on child elements to control its behavior (like the Row/Column information). Instead of associating all of these properties with every element, any object is allowed to provide property definitions for any other object. This is similar to the "expando" features of JavaScript.

System.Windows.Media.Visual

With a system defined, the next step is getting pixels drawn to the screen. The Visual class provides for building a tree of visual objects, each optionally containing drawing instructions and metadata about how to render those instructions (clipping, transformation, etc.). Visual is designed to be extremely lightweight and flexible, so most of the features have no public API exposure and rely heavily on protected callback functions. Visual is really the entry point to the WPF composition system. Visual is the point of connection between these two subsystems, the managed API and the unmanaged milcore. WPF displays data by traversing the unmanaged data structures managed by the milcore. These structures, called composition nodes, represent a hierarchical display tree with rendering instructions at each node. This tree, illustrated on the right hand side of the figure below, is only accessible through a messaging protocol. When programming WPF, you create Visual elements, and derived types, which internally communicate to the composition tree through this messaging protocol. Each Visual in WPF may create one, none, or several composition nodes.

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

There is a very important architectural detail to notice here the entire tree of visuals and drawing instructions is cached. In graphics terms, WPF uses a retained rendering system. This enables the system to repaint at high refresh rates without the composition system blocking on callbacks to user code. This helps prevent the appearance of an unresponsive application. Another important detail that isnt really noticeable in the diagram is how the system actually performs composition. In User32 and GDI, the system works on an immediate mode clipping system. When a component needs to be rendered, the system establishes a clipping bounds outside of which the component isnt allowed to touch the pixels, and then the component is asked to paint pixels in that box. This system works very well in memory constrained systems because when something changes you only have to touch the affected component no two components ever contribute to the color of a single pixel. WPF uses a "painter's algorithm" painting model. This means that instead of clipping each component, each component is asked to render from the back to the front of the display. This allows each component to paint over the previous component's display. The advantage of this model is that you can have complex, partially transparent shapes. With todays modern graphics hardware, this model is relatively fast (which wasnt the case when User32/ GDI were created). As mentioned previously, a core philosophy of WPF is to move to a more declarative, "property centric" model of programming. In the visual system, this shows up in a couple of interesting places. First, if you think about the retained mode graphic system, this is really moving away from an imperative DrawLine/DrawLine type model, to a data oriented model new Line()/new Line(). This move to data driven rendering allows complex operations on the drawing instructions to be expressed using properties. The types deriving from Drawing are effectively the object model for rendering. Second, if you evaluate the animation system, you'll see that it is almost completely declarative. Instead of requiring a developer to compute the next location, or next color, you can express animations as a set of properties on an animation object. These animations can then express the intent of the developer or designer (move this button from here to there in 5 seconds), and the system can determine the most efficient way to accomplish that.

System.Windows.UIElement

UIElement defines core subsystems including Layout, Input, and Events. Layout is a core concept in WPF. In many systems there is either a fixed set of layout models (HTML supports three models for layout; flow, absolute, and tables) or no model for layout (User32 really only supports absolute positioning). WPF started with the assumption that developers and designers wanted a flexible, extensible layout model, which could be driven by property values

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

rather than imperative logic. At the UIElement level, the basic contract for layout is introduced a two phase model with Measure and Arrange passes. Measure allows a component to determine how much size it would like to take. This is a separate phase from Arrange because there are many situations where a parent element will ask a child to measure several times to determine its optimal position and size. The fact that parent elements ask child elements to measure demonstrates another key philosophy of WPF size to content. All controls in WPF support the ability to size to the natural size of their content. This makes localization much easier, and allows for dynamic layout of elements as things resize. The Arrange phase allows a parent to position and determine the final size of each child. A lot of time is often spent talking about the output side of WPF Visual and related objects. However there is a tremendous amount of innovation on the input side as well. Probably the most fundamental change in the input model for WPF is the consistent model by which input events are routed through the system. Input originates as a signal on a kernel mode device driver and gets routed to the correct process and thread through an intricate process involving the Windows kernel and User32. Once the User32 message corresponding to the input is routed to WPF, it is converted into a WPF raw input message and sent to the dispatcher. WPF allows for raw input events to be converted to multiple actual events, enabling features like "MouseEnter" to be implemented at a low level of the system with guaranteed delivery. Each input event is converted to at least two events a "preview" event and the actual event. All events in WPF have a notion of routing through the element tree. Events are said to "bubble" if they traverse from a target up the tree to the root, and are said to "tunnel" if that start at the root and traverse down to a target. Input preview events tunnel, enabling any element in the tree an opportunity to filter or take action on the event. The regular (non-preview) events then bubble from the target up to the root. This split between the tunnel and bubble phase makes implementation of features like keyboard accelerators work in a consistent fashion in a composite world. In User32 you would implement keyboard accelerators by having a single global table containing all the accelerators you wanted to support (Ctrl+N mapping to "New"). In the dispatcher for your application you would call TranslateAccelerator which would sniff the input messages in User32 and determine if any matched a registered accelerator. In WPF this wouldnt work because the system is fully "composable" any element can handle and use any keyboard accelerator. Having this two phase model for input allows components to implement their own "TranslateAccelerator". To take this one step further, UIElement also introduces the notion of CommandBindings. The WPF command system allows developers to define functionality in terms of a command end point something that implements ICommand. Command bindings enable an element to define a mapping between an input gesture (Ctrl+N) and a command (New). Both the input gestures and command definitions are extensible, and can be wired together at usage time. This makes it trivial, for example, to allow an end user to customize the key bindings that they want to use within an application. To this point in the topic, "core" features of WPF features implemented in the PresentationCore assembly, have been the focus. When building WPF, a clean separation between foundational pieces (like the contract for layout with Measure and Arrange) and framework pieces (like the implementation of a specific layout like Grid) was the desired outcome. The goal was to provide an extensibility point low in the stack that would allow external developers to create their own frameworks if needed.

System.Windows.FrameworkElement

FrameworkElement can be looked at in two different ways. It introduces a set of policies and customizations on the subsystems introduced in lower layers of WPF. It also introduces a set of new subsystems. The primary policy introduced by FrameworkElement is around application layout. FrameworkElement builds on the basic layout contract introduced by UIElement and adds the notion of a layout "slot" that makes it easier for layout authors to have a consistent set of property driven layout semantics. Properties like HorizontalAlignment, VerticalAlignment, MinWidth, and Margin (to name a few) give all components derived from FrameworkElement consistent behavior inside of layout containers. FrameworkElement also provides easier API exposure to many features found in the core layers of WPF. For example, FrameworkElement provides direct access to animation through the BeginStoryboard method. A Storyboard provides a way to script multiple animations against a set of properties.

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

The two most critical things that FrameworkElement introduces are data binding and styles. The data binding subsystem in WPF should be relatively familiar to anyone that has used Windows Forms or ASP.NET for creating an application user interface (UI). In each of these systems, there is a simple way to express that you want one or more properties from a given element to be bound to a piece of data. WPF has full support for property binding, transformation, and list binding. One of the most interesting features of data binding in WPF is the introduction of data templates. Data templates allow you to declaratively specify how a piece of data should be visualized. Instead of creating a custom user interface that can be bound to data, you can instead turn the problem around and let the data determine the display that will be created. Styling is really a lightweight form of data binding. Using styling you can bind a set of properties from a shared definition to one or more instances of an element. Styles get applied to an element either by explicit reference (by setting the Style property) or implicitly by associating a style with the CLR type of the element.

System.Windows.Controls.Control

Controls most significant feature is templating. If you think about WPFs composition system as a retained mode rendering system, templating allows a control to describe its rendering in a parameterized, declarative manner. A ControlTemplate is really nothing more than a script to create a set of child elements, with bindings to properties offered by the control. Control provides a set of stock properties, Foreground, Background, Padding, to name a few, which template authors can then use to customize the display of a control. The implementation of a control provides a data model and interaction model. The interaction model defines a set of commands (like Close for a window) and bindings to input gestures (like clicking the red X in the upper corner of the window). The data model provides a set of properties to either customize the interaction model or customize the display (determined by the template). This split between the data model (properties), interaction model (commands and events), and display model (templates) enables complete customization of a controls look and behavior. A common aspect of the data model of controls is the content model. If you look at a control like Button, you will see that it has a property named "Content" of type Object. In Windows Forms and ASP.NET, this property would typically be a string however that limits the type of content you can put in a button. Content for a button can either be a simple string, a complex data object, or an entire element tree. In the case of a data object, the data template is used to construct a display.

Summary

WPF is designed to allow you to create dynamic, data driven presentation systems. Every part of the system is designed to create objects through property sets that drive behavior. Data binding is a fundamental part of the system, and is integrated at every layer. Traditional applications create a display and then bind to some data. In WPF, everything about the control, every aspect of the display, is generated by some type of data binding. The text found inside a button is displayed by creating a composed control inside of the button and binding its display to the buttons content property. When you begin developing WPF based applications, it should feel very familiar. You can set properties, use objects, and data bind in much the same way that you can using Windows Forms or ASP.NET. With a deeper investigation into the architecture of WPF, you'll find that the possibility exists for creating much richer applications that fundamentally treat data as the core driver of the application.

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

WPF Architecture

See Also

Reference

Visual UIElement ICommand FrameworkElement DispatcherObject CommandBinding Control


Concepts

Data Binding Overview Layout System Animation Overview

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/ms750441.aspx[6/18/2010 12:14:17 PM]

What's New in WPF Version 4

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

.NET Framework 4 - Windows Presentation Foundation

What's New in WPF Version 4

This topic contains information about new and enhanced features in Windows Presentation Foundation (WPF) version 4. This topic contains the following sections: New Controls Visual State Manager Touch and Manipulation Graphics and Animations Text Binding XAML Browser Applications WPF and Windows WPF and Silverlight Designer

New Controls

Three new controls have been added to WPF to make it easier to create business applications. These controls are almost 100 percent compatible with the Silverlight versions. This enables developers to reuse code and quickly create client and Web versions. DataGrid Calendar DatePicker

Visual State Manager

WPF provides better support for changing visual states in a ControlTemplate. The VisualStateManager class and supporting classes have been added so that tools such as Microsoft Expression Blend can be used to define a control's appearance according to its visual state. For example, you can define the appearance of a Button control when it is in the Pressed state. For more information about creating a ControlTemplate that uses the VisualStateManager for an existing control, see Customizing the Appearance of an Existing Control by Creating a ControlTemplate. For information about creating a new control that uses the

http://msdn.microsoft.com/en-us/library/bb613588.aspx[6/18/2010 12:15:28 PM]

What's New in WPF Version 4

VisualStateManager, see Creating a Control That Has a Customizable Appearance.

Note
Elements can take advantage of the VisualStateManager outside of a ControlTemplate by using the GoToElementState method.

Touch and Manipulation

Elements in WPF now accept touch input. The UIElement, and UIElement3D, and ContentElement classes expose events that occur when a user touches an element on a touch-enabled screen. In addition to the touch events, the UIElement supports manipulation. A manipulation is interpreted to scale, rotate, or translate the UIElement. For example, a photo viewing application might allow users to move, zoom, resize, and rotate a photo by touching the computer screen over the photo. For more information about touch, see Walkthrough: Creating Your First Touch Application and Input Overview.

Graphics and Animations

Several changes have been made related to graphics and animations. Layout Rounding When an object edge falls in the middle of a pixel device, the DPI-independent graphics system can create rendering artifacts, such as blurry or semi-transparent edges. Previous versions of WPF included pixel snapping to help handle this case. Silverlight 2 introduced layout rounding, which is another way to move elements so that edges fall on whole pixel boundaries. WPF now supports layout rounding with the UseLayoutRounding attached property on FrameworkElement. Cached Composition By using the new BitmapCache and BitmapCacheBrush classes, you can cache a complex part of the visual tree as a bitmap and greatly improve rendering time. The bitmap remains responsive to user input, such as mouse clicks, and you can paint it onto other elements just like any brush. Pixel Shader 3 Support WPF 4 builds on top of the ShaderEffect support introduced in WPF 3.5 SP1 by allowing applications to now write effects by using Pixel Shader (PS) version 3.0. The PS 3.0 shader model is more sophisticated than PS 2.0, which allows for even more effects on supported hardware. Easing Functions You can enhance animations with easing functions, which give you additional control over the behavior of animations. For example, you can apply an ElasticEase to an animation to give the animation a springy behavior. For more information, see the easing types in the System.Windows.Media.Animation namespace.

Text

http://msdn.microsoft.com/en-us/library/bb613588.aspx[6/18/2010 12:15:28 PM]

What's New in WPF Version 4

Several changes have been made related to text. New Text Rendering Stack The WPF text rendering stack has been completely replaced. This change brings improvements to text rendering configurability, clarity, and support for international languages. The new text stack now supports explicitly selecting aliased, grayscale, or ClearType rendering modes. The text stack now supports display-optimized character layout, to produce text with sharpness comparable to Win32/GDI text. The new text stack allows optimizing text hinting and snapping for either animated or static text. The new text stack also supports fonts with embedded bitmaps to be substituted for smaller font sizes, allowing many East Asian fonts to render with sharpness comparable to Win32/GDI text. Selection and Caret Customization You can now specify the brush that paints the selection and caret for input and reading controls, such as TextBoxRichTextBox, and FlowDocumentReader. There are two new properties on TextBoxBase: SelectionBrush allows you to create a brush for highlighting selected text. CaretBrush allows you to change the brush that paints the cursor.

Binding

Various changes and enhancements have been made related to binding. Bind to commands on InputBinding. You can bind the Command property of an InputBinding class to an instance that is defined in code. The following properties are dependency properties, so that they can be targets of bindings: InputBinding.Command InputBinding.CommandParameter InputBinding.CommandTarget KeyBinding.Key KeyBinding.Modifiers MouseBinding.MouseAction The InputBinding, MouseBinding, and KeyBinding classes receive data context from the owning FrameworkElement. Bind to Dynamic Objects WPF supports data binding to objects that implement IDynamicMetaObjectProvider. For example, if you create a dynamic object that inherits from DynamicObject in code, you can use markup extension to bind to the object in XAML. For more information, see the Binding Sources Overview. Bindable Text Run Run.Text is now a dependency property. The main advantage is that it now supports one-way bindings. It also supports other features of dependency properties, such as styling and templating.

http://msdn.microsoft.com/en-us/library/bb613588.aspx[6/18/2010 12:15:28 PM]

What's New in WPF Version 4

XAML Browser Applications

Two features have been added to XAML browser applications (XBAPs). HTML-XBAP Script Interop You can now communicate with the Web page containing the XBAP when the application is hosted in a HTML frame. The XBAP can get deep access to the HTML DOM and can handle DOM events. For more information see BrowserInteropHelper.HostScript. Full-Trust XBAP Deployment If your XBAP requires full trust, the user will now automatically receive the standard ClickOnce elevation prompt when they install the application from the intranet or one of their browser's trusted sites. For more information on both these features, see WPF XAML Browser Applications Overview.

WPF and Windows

The Windows 7 taskbar provides enhanced functionality that enables you to use the taskbar button to communicate status to a user and expose common tasks. New types in the System.Windows.Shell namespace provide managed wrappers for functionality in the Windows 7 taskbar and manages the data passed to the Windows shell. For example, the JumpList type allows you to work with Jump Lists and the TaskbarItemInfo type allows you to work with taskbar thumbnails. WPF dialog boxes on Windows 7 and Windows Vista now support the look and feel of the Windows 7 and Windows Vista style, which includes custom places. For more information, see the FileDialogCustomPlace class.

WPF and Silverlight Designer

In Visual Studio 2010, various designer improvements have been made to help create WPF or Silverlight applications. Improved Support for Silverlight In Visual Studio 2008, you could install the Silverlight Tools to create Silverlight applications in Visual Studio. However, the designer support for Silverlight projects was limited. In Visual Studio 2010, the designer support for Silverlight and WPF projects are now the same. For example, in Silverlight projects you can now select and position items with the mouse on the design surface. Support for Multiple Platform Versions In Visual Studio 2008, control design times were able to target only the latest WPF platform version. In Visual Studio 2010, this support is extended across multiple platforms, including design-time support for WPF 3.5, WPF 4, Silverlight 3, Silverlight 4, and future platform releases. As the same extensibility API exists for all these platforms, control design-time authors can easily write one experience and share it across the control runtimes for each platform. Visual Databinding

http://msdn.microsoft.com/en-us/library/bb613588.aspx[6/18/2010 12:15:28 PM]

What's New in WPF Version 4

The new data binding builder enables visual construction and editing of bindings without typing XAML. Auto Layout Layout improvements include a more intuitive Grid designer and better support for automatically sizing user controls. Improved Property Editing The Properties window now enables visually creating and editing Brush resources. For more information, see WPF Designer.

See Also

Concepts

What's New in the .NET Framework 4

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/bb613588.aspx[6/18/2010 12:15:28 PM]

Walkthrough: Getting Started with WPF

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

.NET Framework 4 - Windows Presentation Foundation

Walkthrough: Getting Started with WPF

This walkthrough provides an introduction to the development of a Windows Presentation Foundation (WPF) application that includes the elements that are common to most WPF applications: Extensible Application Markup Language (XAML) markup, code-behind, application definitions, controls, layout, data binding, and styles. This walkthrough guides you through the development of a simple WPF application using the following steps. Defining XAML to design the appearance of the application's user interface (UI). Writing code to build the application's behavior. Creating an application definition to manage the application. Adding controls and creating the layout to compose the application UI. Creating styles to create a consistent appearance throughout an application's UI. Binding the UI to data to both populate the UI from data and keep the data and UI synchronized. By the end of the walkthrough, you will have built a standalone Windows application that allows users to view expense reports for selected people. The application will be composed of several WPF pages that are hosted in a browser-style window. The sample code that is used to build this walkthrough is available for both Microsoft Visual Basic and C# at Introduction to Building WPF Applications.

Prerequisites

You need the following components to complete this walkthrough: Visual Studio 2010 For more information about installing Visual Studio, see Installing Visual Studio.

Creating the Application Project

In this section, you create the application infrastructure, which includes an application definition, two pages, and an image. 1. Create a new WPF Application project in Visual Basic or Visual C# named ExpenseIt. For more information, see How to: Create a New WPF Application Project. 2. Open Application.xaml (Visual Basic) or App.xaml (C#).

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

This XAML file defines a WPF application and any application resources. You also use this file to specify the UI that automatically shows when the application starts; in this case, MainWindow.xaml. Your XAML should look like this in Visual Basic: XAML
<Application x:Class="Application" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> </Application.Resources> </Application>

Copy

Or like this in C#: XAML


<Application x:Class="ExpenseIt.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"> <Application.Resources> </Application.Resources> </Application>

Copy

3. Open MainWindow.xaml. This XAML file is the main window of your application and displays content created in pages. The Window class defines the properties of a window, such as its title, size, or icon, and handles events, such as closing or hiding. 4. Change the Window element to a NavigationWindow. This application will navigate to different content depending on the user interaction. Therefore, the main Window needs to be changed to a NavigationWindow. NavigationWindow inherits all the properties of Window. The NavigationWindow element in the XAML file creates an instance of the NavigationWindow class. For more information, see Navigation Overview. 5. Change the following properties on the NavigationWindow element: Set the Title property to "ExpenseIt". Set the Width property to 500 pixels. Set the Height property to 350 pixels. Remove the Grid elements between the NavigationWindow tags. Your XAML should look like this in Visual Basic: XAML
<NavigationWindow x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ExpenseIt" Height="350" Width="500"> </NavigationWindow>

Or like this in C#: XAML


<NavigationWindow x:Class="ExpenseIt.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ExpenseIt" Height="350" Width="500"> </NavigationWindow>

Copy

6. Open MainWindow.xaml.vb or MainWindow.xaml.cs. This file is a code-behind file that contains code to handle the events declared in MainWindow.xaml. This file contains a partial class for the window defined in XAML. 7. If you are using C#, change the MainWindow class to derive from NavigationWindow. In Visual Basic, this happens automatically when you change the window in XAML. Your code should look like this. VB C# C++ F# JScript

Copy

Class MainWindow End Class

Adding Files to the Application

In this section, you add two pages and an image to the application. 1. Add a new Page (WPF) to the project named ExpenseItHome.xaml. For more information, see How to: Add New Items to a WPF Project. This page is the first page that is displayed when the application is launched. It will show a list of people from which a user can select a person to show an expense report for. 2. Open ExpenseItHome.xaml. 3. Set the Title to "ExpenseIt - Home". Your XAML should look like this in Visual Basic:

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

XAML
<Page x:Class="ExpenseItHome" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="ExpenseIt - Home"> <Grid> </Grid> </Page>

Copy

Or this in C#: XAML


<Page x:Class="ExpenseIt.ExpenseItHome" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="ExpenseIt - Home"> <Grid> </Grid> </Page>

Copy

4. Open MainWindow.xaml. 5. Set the Source property on the NavigationWindow to "ExpenseItHome.xaml". This sets ExpenseItHome.xaml to be the first page opened when the application starts. Your XAML should look like this in Visual Basic: XAML
<NavigationWindow x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml"> </NavigationWindow>

Copy

Or this in C#: XAML


<NavigationWindow x:Class="ExpenseIt.MainWindow"

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ExpenseIt" Height="350" Width="500" Source="ExpenseItHome.xaml"> </NavigationWindow>

6. Add a new Page (WPF) to the project named ExpenseReportPage.xaml. This page will show the expense report for the person that is selected on ExpenseItHome.xaml. 7. Open ExpenseReportPage.xaml. 8. Set the Title to "ExpenseIt - View Expense". Your XAML should look like this in Visual Basic: XAML
<Page x:Class="ExpenseReportPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="ExpenseIt - View Expense"> <Grid> </Grid> </Page>

Copy

Or this in C#: XAML


<Page x:Class="ExpenseIt.ExpenseReportPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="ExpenseIt - View Expense"> <Grid> </Grid> </Page>

Copy

9. Open ExpenseItHome.xaml.vb and ExpenseReportPage.xaml.vb, or ExpenseItHome.xaml.cs and ExpenseReportPage.xaml.cs. When you create a new Page file, Visual Studio automatically creates a code behind file. These code-behind files handle the logic for responding to user input. Your code should look like this.

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

VB

C#

C++

F#

JScript

Copy

Class ExpenseItHome End Class

VB

C#

C++

F#

JScript

Copy

Class ExpenseReportPage End Class

10. Add an image named watermark.png to the project. You can either create your own image, or copy the file from the sample code. For more information, see How to: Add Existing Items to a Project.

Building and Running the Application

In this section, you build and run the application. 1. Build and run the application by pressing F5 or select Start Debugging from the Debug menu. The following illustration shows the application with the NavigationWindow buttons.

2. Close the application to return to Visual Studio.

Creating the Layout

Layout provides an ordered way to place UI elements, and also manages the size and position of those elements when a UI is resized. You typically create a layout with one of the following layout controls: Canvas DockPanel

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

Grid StackPanel VirtualizingStackPanel WrapPanel Each of these layout controls supports a special type of layout for its child elements. ExpenseIt pages can be resized, and each page has elements that are arranged horizontally and vertically alongside other elements. Consequently, the Grid is the ideal layout element for the application.

Note
For more information about Panel elements, see Panels Overview. For more information about layout, see Layout System. In the section, you create a single-column table with three rows and a 10-pixel margin by adding column and row definitions to the Grid in ExpenseItHome.xaml. 1. Open ExpenseItHome.xaml. 2. Set the Margin property on the Grid element to "10,0,10,10" which corresponds to left, top, right and bottom margins. 3. Add the following XAML between the Grid tags to create the row and column definitions. XAML
<Grid.ColumnDefinitions> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>

Copy

The Height of two rows is set to Auto which means that the rows will be sized base on the content in the rows. The default Height is Star sizing, which means that the row will be a weighted proportion of the available space. For example if two rows each have a height of "*", they will each have a height that is half of the available space. Your Grid should now look like the following XAML: XAML
<Grid Margin="10,0,10,10"> <Grid.ColumnDefinitions> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> </Grid>

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

Adding Controls

In this section, the home page UI is updated to show a list of people that users can select from to show the expense report for a selected person. Controls are UI objects that allow users to interact with your application. For more information, see Controls. To create this UI, the following elements are added to ExpenseItHome.xaml: ListBox (for the list of people). Label (for the list header). Button (to click to view the expense report for the person that is selected in the list). Each control is placed in a row of the Grid by setting the Grid.Row attached property. For more information about attached properties, see Attached Properties Overview. 1. Open ExpenseItHome.xaml. 2. Add the following XAML between the Grid tags. XAML
<!-- People list --> <Border Grid.Column="0" Grid.Row="0" Height="35" Padding="5" Background="#4E87D4"> <Label VerticalAlignment="Center" Foreground="White">Names</Label> </Border> <ListBox Name="peopleListBox" Grid.Column="0" Grid.Row="1"> <ListBoxItem>Mike</ListBoxItem> <ListBoxItem>Lisa</ListBoxItem> <ListBoxItem>John</ListBoxItem> <ListBoxItem>Mary</ListBoxItem> </ListBox> <!-- View report button --> <Button Grid.Column="0" Grid.Row="2" Margin="0,10,0,0" Width="125" Height="25" HorizontalAlignment="Right">View</Button>

Copy

3. Build and run the application. The following illustration shows the controls that are created by the XAML in this section.

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

Adding an Image and a Title

In this section, the home page UI is updated with an image and a page title. 1. Open ExpenseItHome.xaml. 2. Add another column to the ColumnDefinitions with a fixed Width of 230 pixels. XAML
<Grid.ColumnDefinitions> <ColumnDefinition Width="230" /> <ColumnDefinition /> </Grid.ColumnDefinitions>

Copy

3. Add another row to the RowDefinitions. XAML


<Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>

Copy

4. Move the controls to the second column by setting Grid.Column to 1. Move each control down a row, by increasing the Grid.Row by 1. XAML
<Border Grid.Column="1" Grid.Row="1" Height="35" Padding="5" Background="#4E87D4"> <Label VerticalAlignment="Center" Foreground="White">Names</Label> </Border> <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2"> <ListBoxItem>Mike</ListBoxItem> <ListBoxItem>Lisa</ListBoxItem> <ListBoxItem>John</ListBoxItem> <ListBoxItem>Mary</ListBoxItem> </ListBox> <!-- View report button --> <Button Grid.Column="1" Grid.Row="3" Margin="0,10,0,0" Width="125" Height="25" HorizontalAlignment="Right">View</Button>

Copy

5. Set the Background of the Grid to be the watermark.png image file.

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

XAML
<Grid.Background> <ImageBrush ImageSource="watermark.png"/> </Grid.Background>

Copy

6. Before the Border, add a Label with the content "View Expense Report" to be the title of the page. XAML
<Label Grid.Column="1" VerticalAlignment="Center" FontFamily="Trebuchet MS" FontWeight="Bold" FontSize="18" Foreground="#0066cc"> View Expense Report </Label>

Copy

7. Build and run the application. The following illustration shows the results of this section.

Adding Code to Handle Events

1. Open ExpenseItHome.xaml. 2. Add a Click event handler to the Button element. For more information, see How to: Create a Simple Event Handler. XAML
<!-- View report button -->

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


<Button Grid.Column="1" Grid.Row="3" Margin="0,10,0,0" Width="125" Height="25" HorizontalAlignment="Right" Click="Button_Click">View</Button>

3. Open ExpenseItHome.xaml.vb or ExpenseItHome.xaml.cs. 4. Add the following code to the Click event handler, which causes the window to navigate to the ExpenseReportPage.xaml file. VB C# C++ F# JScript

Copy

Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) ' View Expense Report Dim expenseReportPage As New ExpenseReportPage() Me.NavigationService.Navigate(expenseReportPage) End Sub

Creating the UI for ExpenseReportPage

ExpenseReportPage.xaml displays the expense report for the person that was selected on the ExpenseItHome.xaml. This section adds controls and creates the UI for ExpenseReportPage.xaml. This section also adds background and fill colors to the various UI elements. 1. Open ExpenseReportPage.xaml. 2. Add the following XAML between the Grid tags. This UI is similar to the UI created on ExpenseItHome.xaml except the report data is displayed in a DataGrid. XAML
<Grid.Background> <ImageBrush ImageSource="watermark.png" /> </Grid.Background> <Grid.ColumnDefinitions> <ColumnDefinition Width="230" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions>

Copy

<Label Grid.Column="1" VerticalAlignment="Center" FontFamily="Trebuchet MS" FontWeight="Bold" FontSize="18" Foreground="#0066cc"> Expense Report For: </Label> <Grid Margin="10" Grid.Column="1" Grid.Row="1"> <Grid.ColumnDefinitions>

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


<ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <!-- Name --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal"> <Label Margin="0,0,0,5" FontWeight="Bold">Name:</Label> <Label Margin="0,0,0,5" FontWeight="Bold"></Label> </StackPanel> <!-- Department --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal"> <Label Margin="0,0,0,5" FontWeight="Bold">Department:</Label> <Label Margin="0,0,0,5" FontWeight="Bold"></Label> </StackPanel> <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left"> <!-- Expense type and Amount table --> <DataGrid AutoGenerateColumns="False" RowHeaderWidth="0" > <DataGrid.ColumnHeaderStyle> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="Height" Value="35" /> <Setter Property="Padding" Value="5" /> <Setter Property="Background" Value="#4E87D4" /> <Setter Property="Foreground" Value="White" /> </Style> </DataGrid.ColumnHeaderStyle> <DataGrid.Columns> <DataGridTextColumn Header="ExpenseType" /> <DataGridTextColumn Header="Amount" /> </DataGrid.Columns> </DataGrid> </Grid> </Grid>

3. Build and run the application. 4. Click the View button. The expense report page appears. The following illustration shows the UI elements added to ExpenseReportPage.xaml. Notice that the back navigation button is enabled.

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

Styling Controls

The appearance of various elements can often be the same for all elements of the same type in a UI. UI uses styles to make appearances reusable across multiple elements. The reusability of styles helps to simplify XAML creation and management. For more information about styles, see Styling and Templating. This section replaces the per-element attributes that were defined in previous steps with styles. 1. Open Application.xaml or App.xaml. 2. Add the following XAML between the Application.Resources tags: XAML
<!-- Header text style --> <Style x:Key="headerTextStyle"> <Setter Property="Label.VerticalAlignment" Value="Center"></Setter> <Setter Property="Label.FontFamily" Value="Trebuchet MS"></Setter> <Setter Property="Label.FontWeight" Value="Bold"></Setter> <Setter Property="Label.FontSize" Value="18"></Setter> <Setter Property="Label.Foreground" Value="#0066cc"></Setter> </Style> <!-- Label style --> <Style x:Key="labelStyle" TargetType="{x:Type Label}"> <Setter Property="VerticalAlignment" Value="Top" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="FontWeight" Value="Bold" /> <Setter Property="Margin" Value="0,0,0,5" /> </Style> <!-- DataGrid header style --> <Style x:Key="columnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="Height" Value="35" /> <Setter Property="Padding" Value="5" /> <Setter Property="Background" Value="#4E87D4" /> <Setter Property="Foreground" Value="White" /> </Style>

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


<!-- List header style --> <Style x:Key="listHeaderStyle" TargetType="{x:Type Border}"> <Setter Property="Height" Value="35" /> <Setter Property="Padding" Value="5" /> <Setter Property="Background" Value="#4E87D4" /> </Style> <!-- List header text style --> <Style x:Key="listHeaderTextStyle" TargetType="{x:Type Label}"> <Setter Property="Foreground" Value="White" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="HorizontalAlignment" Value="Left" /> </Style> <!-- Button style --> <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Setter Property="Width" Value="125" /> <Setter Property="Height" Value="25" /> <Setter Property="Margin" Value="0,10,0,0" /> <Setter Property="HorizontalAlignment" Value="Right" /> </Style>

This XAML adds the following styles: headerTextStyle: To format the page title Label. labelStyle: To format the Label controls. columnHeaderStyle: To format the DataGridColumnHeader. listHeaderStyle: To format the list header Border controls. listHeaderTextStyle: To format the list header Label. buttonStyle: To format the Button on ExpenseItHome.xaml. Notice that the styles are resources and children of the Application.Resources property element. In this location, the styles are applied to all the elements in an application. For an example of using resources in a .NET Framework application, see How to: Use Application Resources. 3. Open ExpenseItHome.xaml. 4. Replace everything between the Grid elements with the following XAML. XAML
<Grid.Background> <ImageBrush ImageSource="watermark.png" </Grid.Background> <Grid.ColumnDefinitions> <ColumnDefinition Width="230" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> />

Copy

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


<!-- People list --> <Label Grid.Column="1" Style="{StaticResource headerTextStyle}" > View Expense Report </Label> <Border Grid.Column="1" Grid.Row="1" Style="{StaticResource listHeaderStyle}"> <Label Style="{StaticResource listHeaderTextStyle}">Names</Label> </Border> <ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2"> <ListBoxItem>Mike</ListBoxItem> <ListBoxItem>Lisa</ListBoxItem> <ListBoxItem>John</ListBoxItem> <ListBoxItem>Mary</ListBoxItem> </ListBox> <!-- View report button --> <Button Grid.Column="1" Grid.Row="3" Click="Button_Click" Style="{StaticResource buttonStyle}">View</Butto n>

The properties such as VerticalAlignment and FontFamily that define the look of each control are removed and replaced by applying the styles. For example, the headerTextStyle is applied to the "View Expense Report" Label. 5. Open ExpenseReportPage.xaml. 6. Replace everything between the Grid elements with the following XAML. XAML
<Grid.Background> <ImageBrush ImageSource="watermark.png" /> </Grid.Background> <Grid.ColumnDefinitions> <ColumnDefinition Width="230" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions>

Copy

<Label Grid.Column="1" Style="{StaticResource headerTextStyle}"> Expense Report For: </Label> <Grid Margin="10" Grid.Column="1" Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <!-- Name --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal"> <Label Style="{StaticResource labelStyle}">Name:</Label> <Label Style="{StaticResource labelStyle}"></Label>

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


</StackPanel> <!-- Department --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal"> <Label Style="{StaticResource labelStyle}">Department:</Label> <Label Style="{StaticResource labelStyle}"></Label> </StackPanel> <Grid Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left"> <!-- Expense type and Amount table --> <DataGrid ColumnHeaderStyle="{StaticResource columnHeaderStyle}" AutoGenerateColumns="False" RowHeaderWidth="0" > <DataGrid.Columns> <DataGridTextColumn Header="ExpenseType" /> <DataGridTextColumn Header="Amount" /> </DataGrid.Columns> </DataGrid> </Grid> </Grid>

This adds styles to the Label and Border elements. 7. Build and run the application. After adding the XAML in this section, the application looks the same as it did before being updated with styles.

Binding Data to a Control

In this section, you create the XML data that is bound to various controls. 1. Open ExpenseItHome.xaml. 2. In the Grid element, add the following XAML to create an XmlDataProvider that contains the data for each person. The data is created as a Grid resource. Normally this would be loaded as a file, but for simplicity the data is added inline. XAML
<Grid.Resources>

Copy

...

<!-- Expense Report Data --> <XmlDataProvider x:Key="ExpenseDataSource" XPath="Expenses"> <x:XData> <Expenses xmlns=""> <Person Name="Mike" Department="Legal"> <Expense ExpenseType="Lunch" ExpenseAmount="50" /> <Expense ExpenseType="Transportation" ExpenseAmount="50" /> </Person> <Person Name="Lisa" Department="Marketing">

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF


<Expense ExpenseType="Document printing" ExpenseAmount="50"/> <Expense ExpenseType="Gift" ExpenseAmount="125" /> </Person> <Person Name="John" Department="Engineering"> <Expense ExpenseType="Magazine subscription" ExpenseAmount="50"/> <Expense ExpenseType="New machine" ExpenseAmount="600" /> <Expense ExpenseType="Software" ExpenseAmount="500" /> </Person> <Person Name="Mary" Department="Finance"> <Expense ExpenseType="Dinner" ExpenseAmount="100" /> </Person> </Expenses> </x:XData> </XmlDataProvider>

...

</Grid.Resources>

3. In the Grid resource, add the following DataTemplate, which defines how to display the data in the ListBox. For more information about data templates, see Data Templating Overview. XAML
<Grid.Resources>

Copy

...

<!-- Name item template --> <DataTemplate x:Key="nameItemTemplate"> <Label Content="{Binding XPath=@Name}"/> </DataTemplate>

...

</Grid.Resources>

4. Replace the existing ListBox with the following XAML. XAML


<ListBox Name="peopleListBox" Grid.Column="1" Grid.Row="2" ItemsSource="{Binding Source={StaticResource ExpenseDataSource}, XPath=Person}" ItemTemplate="{StaticResource nameItemTemplate}"> </ListBox>

Copy

This XAML binds the ItemsSource property of the ListBox to the data source and applies the data template as the

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

ItemTemplate.

Connecting Data to Controls

In this section, you write the code that retrieves the current item that is selected in the list of people on the ExpenseItHome.xaml page, and passes its reference to the constructor of ExpenseReportPage during instantiation. ExpenseReportPage sets its data context with the passed item, which is what the controls defined in ExpenseReportPage.xaml will bind to. 1. Open ExpenseReportPage.xaml.vb or ExpenseReportPage.xaml.cs. 2. Add a constructor that takes an object so you can pass the expense report data of the selected person. VB C# C++ F# JScript

Copy

Partial Public Class ExpenseReportPage Inherits Page Public Sub New() InitializeComponent() End Sub ' Custom constructor to pass expense report data Public Sub New(ByVal data As Object) Me.New() ' Bind to expense report data. Me.DataContext = data End Sub End Class

3. Open ExpenseItHome.xaml.vb or ExpenseItHome.xaml.cs. 4. Change the Click event handler to call the new constructor passing the expense report data of the selected person. VB C# C++ F# JScript

Copy

Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) ' View Expense Report Dim expenseReportPage As New ExpenseReportPage(Me.peopleListBox.SelectedItem) Me.NavigationService.Navigate(expenseReportPage) End Sub

Styling Data with Data Templates

In this section, you update the UI for each item in the data bound lists by using data templates.
http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

1. Open ExpenseReportPage.xaml. 2. Bind the content of the "Name" and "Department" Label elements to the appropriate data source property. For more information about data binding, see Data Binding Overview. XAML
<!-- Name --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Orientation="Horizontal"> <Label Style="{StaticResource labelStyle}">Name:</Label> <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=@Name}"></Label> </StackPanel> <!-- Department --> <StackPanel Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" Orientation="Horizontal"> <Label Style="{StaticResource labelStyle}">Department:</Label> <Label Style="{StaticResource labelStyle}" Content="{Binding XPath=@Department}"></Label> </StackPanel>

Copy

3. After the opening Grid element, add the following data templates, which define how to display the expense report data. XAML
<!--Templates to display expense report data--> <Grid.Resources> <!-- Reason item template --> <DataTemplate x:Key="typeItemTemplate"> <Label Content="{Binding XPath=@ExpenseType}"/> </DataTemplate> <!-- Amount item template --> <DataTemplate x:Key="amountItemTemplate"> <Label Content="{Binding XPath=@ExpenseAmount}"/> </DataTemplate> </Grid.Resources>

Copy

4. Apply the templates to the DataGrid columns that display the expense report data. XAML

Copy

<!-- Expense type and Amount table --> <DataGrid ItemsSource="{Binding XPath=Expense}" ColumnHeaderStyle="{StaticResource columnHeaderStyle}" AutoG enerateColumns="False" RowHeaderWidth="0" > <DataGrid.Columns> <DataGridTextColumn Header="ExpenseType" Binding="{Binding XPath=@ExpenseType}" /> <DataGridTextColumn Header="Amount" Binding="{Binding XPath=@ExpenseAmount}" /> </DataGrid.Columns> </DataGrid>

5. Build and run the application. 6. Select a person and click the View button.

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

The following illustration shows both pages of the ExpenseIt application with controls, layout, styles, data binding, and data templates applied.

Best Practices

This sample demonstrates a specific feature of WPF and, consequently, does not follow application development best practices. For comprehensive coverage of WPF and the .NET Framework application development best practices, see the following topics as appropriate: Accessibility - Accessibility Best Practices Security - Security (WPF) Localization - WPF Globalization and Localization Overview Performance - Optimizing WPF Application Performance

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

Walkthrough: Getting Started with WPF

What's Next

You now have a number of techniques at your disposal for creating a UI using Windows Presentation Foundation (WPF). You should now have a broad understanding of the basic building blocks of a data-bound .NET Framework application. This topic is by no means exhaustive, but hopefully you also now have a sense of some of the possibilities you might discover on your own beyond the techniques in this topic. For more information about the WPF architecture and programming models, see the following topics: WPF Architecture XAML Overview (WPF) Dependency Properties Overview Layout System For more information about creating applications, see the following topics: Application Development Controls Data Binding Overview Graphics and Multimedia Documents in WPF

See Also

Concepts

Panels Overview Data Templating Overview Building a WPF Application (WPF)


Other Resources

Styles and Templates

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/ms752299.aspx[6/18/2010 12:15:51 PM]

XAML Overview (WPF)

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

.NET Framework 4 - Windows Presentation Foundation

XAML Overview (WPF)

This topic describes the features of the XAML language and demonstrates how you can use XAML to write Windows Presentation Foundation (WPF) applications. This topic specifically describes XAML as implemented by WPF. XAML itself is a larger language concept than WPF. This topic contains the following sections. What is XAML? XAML Syntax in Brief Case and Whitespace in XAML Markup Extensions Type Converters XAML Root Elements and XAML Namespaces Custom Prefixes and Custom Types in XAML Events and XAML Code-Behind XAML Named Elements Attached Properties and Attached Events Base Types and XAML XAML Security Loading XAML from Code What's Next Related Topics

What is XAML?

XAML is a declarative markup language. As applied to the .NET Framework programming model, XAML simplifies creating a UI for a .NET Framework application. You can create visible UI elements in the declarative XAML markup, and then separate the UI definition from the run-time logic by using code-behind files, joined to the markup through partial class definitions. XAML directly represents the instantiation of objects in a specific set of backing types defined in assemblies. This is unlike most other markup languages, which are typically an interpreted language without such a direct tie to a backing type system. XAML enables a workflow where separate parties can work on the UI and the logic of an application, using potentially different tools. When represented as text, XAML files are XML files that generally have the .xaml extension. The files can be encoded by any XML encoding, but encoding as UTF-8 is typical. The following example shows how you might create a button as part of a UI. This example is just intended to give you a flavor of how XAML represents common UI programming metaphors (it is not a complete sample). XAML
<StackPanel> <Button Content="Click Me"/> </StackPanel>

Copy

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

XAML Syntax in Brief

The following sections explain the basic forms of XAML syntax, and give a short markup example. These sections are not intended to provide complete information about each syntax form, such as how these are represented in the backing type system. For more information about the specifics of XAML syntax for each of the syntax forms introduced in this topic, see XAML Syntax In Detail. Much of the material in the next few sections will be elementary to you, if you have previous familiarity with the XML language. This is a consequence of one of the basic design principles of XAML. XAML The XAML language defines concepts of its own, but these concepts work within the XML language and markup form.

XAML Object Elements


An object element typically declares an instance of a type. That type is defined in the assemblies that provide the backing types for a technology that uses XAML as a language. Object element syntax always starts with an opening angle bracket (<). This is followed by the name of the type where you want to create an instance. (The name can possibly include a prefix, a concept that will be explained later.) After this, you can optionally declare attributes on the object element. To complete the object element tag, end with a closing angle bracket (>). You can instead use a self-closing form that does not have any content, by completing the tag with a forward slash and closing angle bracket in succession (/>). For example, look at the previously shown markup snippet again: XAML
<StackPanel> <Button Content="Click Me"/> </StackPanel>

Copy

This specifies two object elements: <StackPanel> (with content, and a closing tag later), and <Button .../> (the self-closing form, with several attributes). The object elements StackPanel and Button each map to the name of a class that is defined by WPF and is part of the WPF assemblies. When you specify an object element tag, you create an instruction for XAML processing to create a new instance. Each instance is created by calling the default constructor of the underlying type when parsing and loading the XAML.

Attribute Syntax (Properties)


Properties of an object can often be expressed as attributes of the object element. An attribute syntax names the property that is being set in attribute syntax, followed by the assignment operator (=). The value of an attribute is always specified as a string that is contained within quotation marks. Attribute syntax is the most streamlined property setting syntax and is the most intuitive syntax to use for developers who have used markup languages in the past. For example, the following markup creates a button that has red text and a blue background in addition to display text specified as Content. XAML
<Button Background="Blue" Foreground="Red" Content="This is a button"/>

Copy

Property Element Syntax


For some properties of an object element, attribute syntax is not possible, because the object or information necessary to provide

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

the property value cannot be adequately expressed within the quotation mark and string restrictions of attribute syntax. For these cases, a different syntax known as property element syntax can be used. The syntax for the property element start tag is <typeName.propertyName>. Generally, the content of that tag is an object element of the type that the property takes as its value . After specifying content, you must close the property element with an end tag. The syntax for the end tag is </typeName.propertyName>. If an attribute syntax is possible, using the attribute syntax is typically more convenient and enables a more compact markup, but that is often just a matter of style, not a technical limitation. The following example shows the same properties being set as in the previous attribute syntax example, but this time by using property element syntax for all properties of the Button. XAML
<Button> <Button.Background> <SolidColorBrush Color="Blue"/> </Button.Background> <Button.Foreground> <SolidColorBrush Color="Red"/> </Button.Foreground> <Button.Content> This is a button </Button.Content> </Button>

Copy

Collection Syntax
The XAML language includes some optimizations that produce more human-readable markup. One such optimization is that if a particular property takes a collection type, then items that you declare in markup as child elements within that property's value become part of the collection. In this case a collection of child object elements is the value being set to the collection property. The following example shows collection syntax for setting values of the GradientStops property: XAML
<LinearGradientBrush> <LinearGradientBrush.GradientStops> <!-- no explicit new GradientStopCollection, parser knows how to find or create --> <GradientStop Offset="0.0" Color="Red" /> <GradientStop Offset="1.0" Color="Blue" /> </LinearGradientBrush.GradientStops> </LinearGradientBrush>

Copy

XAML Content Properties


XAML specifies a language feature whereby a class can designate exactly one of its properties to be the XAML content property. Child elements of that object element are used to set the value of that content property. In other words, for the content property uniquely, you can omit a property element when setting that property in XAML markup and produce a more visible parent/child metaphor in the markup. For example, Border specifies a content property of Child. The following two Border elements are treated identically. The first one takes advantage of the content property syntax and omits the Border.Child property element. The second one shows Border.Child explicitly. XAML
<Border> <TextBox Width="300"/>

Copy

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)


</Border> <!--explicit equivalent--> <Border> <Border.Child> <TextBox Width="300"/> </Border.Child> </Border>

As a rule of the XAML language, the value of a XAML content property must be given either entirely before or entirely after any other property elements on that object element. For instance, the following markup does not compile: Copy
<Button>I am a <Button.Background>Blue</Button.Background> blue button</Button>

For more information about this restriction on XAML content properties, see the "XAML Content Properties" section of XAML Syntax In Detail.

Text Content
A small number of XAML elements can directly process text as their content. To enable this, one of the following cases must be true: The class must declare a content property, and that content property must be of a type assignable to a string (the type could be Object). For instance, any ContentControl uses Content as its content property and it is type Object, and this supports the following usage on a practical ContentControl such as a Button: <Button>Hello</Button>. The type must declare a type converter, in which case the text content is used as initialization text for that type converter. For example, <Brush>Blue</Brush>. This case is less common in practice. The type must be a known XAML language primitive.

Content Properties and Collection Syntax Combined


Consider this example: XAML
<StackPanel> <Button>First Button</Button> <Button>Second Button</Button> </StackPanel>

Copy

Here, each Button is a child element of StackPanel. This is a streamlined and intuitive markup that omits two tags for two different reasons. Omitted StackPanel.Children property element:StackPanel derives from Panel. Panel defines Panel.Children as its XAML content property. Omitted UIElementCollection object element: The Panel.Children property takes the type UIElementCollection, which implements IList. The collection's element tag can be omitted, based on the XAML rules for processing collections such as IList. (In this case, UIElementCollection actually cannot be instantiated because it does not expose a default constructor, and that is why the UIElementCollection object element is shown commented out). XAML
<StackPanel> <StackPanel.Children> <!--<UIElementCollection>-->

Copy

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)


<Button>First Button</Button> <Button>Second Button</Button> <!--</UIElementCollection>--> </StackPanel.Children> </StackPanel>

Attribute Syntax (Events)


Attribute syntax can also be used for members that are events rather than properties. In this case, the attribute's name is the name of the event. In the WPF implementation of events for XAML, the attribute's value is the name of a handler that implements that event's delegate. For example, the following markup assigns a handler for the Click event to a Button created in markup: XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="ExampleNamespace.ExamplePage"> <Button Click="Button_Click" >Click Me!</Button> </Page>

Copy

There is more to events and XAML in WPF than just this example of the attribute syntax. For example, you might wonder what the ClickHandler referenced here represents and how it is defined. This will be explained in the upcoming section of this topic.

Case and Whitespace in XAML

XAML is generally speaking case sensitive. For purposes of resolving backing types, WPF XAML is case sensitive by the same rules that the CLR is case sensitive. Object elements, property elements, and attribute names must all be specified by using the sensitive casing when compared by name to the underlying type in the assembly, or to a member of a type. XAML language keywords and primitives are also case sensitive. Values are not always case sensitive. Case sensitivity for values will depend on the type converter behavior associated with the property that takes the value, or the property value type. For example, properties that take the Boolean type can take either true or True as equivalent values, but only because the native WPF XAML parser type conversion for string to Boolean already permits these as equivalents. WPF XAML processors and serializers will ignore or drop all nonsignificant whitespace, and will normalize any significant whitespace. This is consistent with the default whitespace behavior recommendations of the XAML specification. This behavior is generally only of consequence when you specify strings within XAML content properties. In simplest terms, XAML converts space, linefeed and tab characters into spaces, and then preserves one space if found at either end of a contiguous string. The full explanation of XAML whitespace handling is not covered in this topic. For details, see Whitespace Processing in XAML.

Markup Extensions

Markup extensions are a XAML language concept. When used to provide the value of an attribute syntax, curly braces ({ and }) indicate a markup extension usage. This usage directs the XAML processing to escape from the general treatment of attribute values as either a literal string or a string-convertible value.

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

The most common markup extensions used in WPF application programming are Binding, used for data binding expressions, and the resource references StaticResource and DynamicResource. By using markup extensions, you can use attribute syntax to provide values for properties even if that property does not support an attribute syntax in general. Markup extensions often use intermediate expression types to enable features such as deferring values or referencing other objects that are only present at run time. For example, the following markup sets the value of the Style property using attribute syntax. The Style property takes an instance of the Style class, which by default could not be instantiated by an attribute syntax string. But in this case, the attribute references a particular markup extension, StaticResource. When that markup extension is processed, it returns a reference to a style that was previously instantiated as a keyed resource in a resource dictionary. XAML
<Page.Resources> <SolidColorBrush x:Key="MyBrush" Color="Gold"/> <Style TargetType="Border" x:Key="PageBackground"> <Setter Property="Background" Value="Blue"/> </Style>

Copy

...

</Page.Resources> <StackPanel> <Border Style="{StaticResource PageBackground}">

...

</Border> </StackPanel>

For a reference listing of all markup extensions for XAML implemented specifically in WPF, see WPF XAML Extensions. For a reference listing of the markup extensions that are defined by System.Xaml and are more widely available for .NET Framework XAML implementations, see XAML Namespace (x:) Language Features. For more information about markup extension concepts, see Markup Extensions and WPF XAML.

Type Converters

In the section, it was stated that the attribute value must be able to be set by a string. The basic, native handling of how strings are converted into other object types or primitive values is based on the String type itself, in addition to native processing for certain types such as DateTime or Uri. But many WPF types or members of those types extend the basic string attribute processing behavior, in such a way that instances of more complex object types can be specified as strings and attributes. The Thickness structure is an example of a type that has a type conversion enabled for XAML usages. Thickness indicates measurements within a nested rectangle and is used as the value for properties such as Margin. By placing a type converter on Thickness, all properties that use a Thickness are easier to specify in XAML because they can be specified as attributes. The following example uses a type conversion and attribute syntax to provide a value for a Margin: XAML

Copy

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)


<Button Margin="10,20,10,30" Content="Click me"/>

The previous attribute syntax example is equivalent to the following more verbose syntax example, where the Margin is instead set through property element syntax containing a Thickness object element. The four key properties of Thickness are set as attributes on the new instance: XAML
<Button Content="Click me"> <Button.Margin> <Thickness Left="10" Top="20" Right="10" Bottom="30"/> </Button.Margin> </Button>

Copy

Note
There are also a limited number of objects where the type conversion is the only public way to set a property to that type without involving a subclass, because the type itself does not have a default constructor. An example is Cursor. For more information on how type conversion and its use for attribute syntax is supported, see TypeConverters and XAML.

XAML Root Elements and XAML Namespaces

A XAML file must have only one root element, in order to be both a well-formed XML file and a valid XAML file. For typical WPF scenarios, you use a root element that has a prominent meaning in the WPF application model (for example, Window or Page for a page, ResourceDictionary for an external dictionary, or Application for the application definition). The following example shows the root element of a typical XAML file for a WPF page, with the root element of Page. XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Copy

...

</Page>

The root element also contains the attributes xmlns and xmlns:x. These attributes indicate to a XAML processor which XAML namespaces contain the type definitions for backing types that the markup will reference as elements. The xmlns attribute specifically indicates the default XAML namespace. Within the default XAML namespace, object elements in the markup can be specified without a prefix. For most WPF application scenarios, and for almost all of the examples given in the WPF sections of the SDK, the default XAML namespace is mapped to the WPF namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation. The xmlns:x attribute indicates an additional XAML namespace, which maps the XAML language namespace http://schemas.microsoft.com/winfx/2006/xaml.
http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

This usage of xmlns to define a scope for usage and mapping of a namescope is consistent with the XML 1.0 specification. XAML namescopes are different from XML namescopes only in that a XAML namescope also implies something about how the namescope's elements are backed by types when it comes to type resolution and parsing the XAML. Note that the xmlns attributes are only strictly necessary on the root element of each XAML file. xmlns definitions will apply to all descendant elements of the root element (this behavior is again consistent with the XML 1.0 specification for xmlns.) xmlns attributes are also permitted on other elements underneath the root, and would apply to any descendant elements of the defining element. However, frequent definition or redefinition of XAML namespaces can result in a XAML markup style that is difficult to read. The WPF implementation of its XAML processor includes an infrastructure that has awareness of the WPF core assemblies. The WPF core assemblies are known to contain the types that support the WPF mappings to the default XAML namespace. This is enabled through configuration that is part of your project build file and the WPF build and project systems. Therefore, declaring the default XAML namespace as the default xmlns is all that is necessary in order to reference XAML elements that come from WPF assemblies.

The x: Prefix
In the previous root element example, the prefix x: was used to map the XAML namespace http://schemas.microsoft.com/winfx/2006/xaml, which is the dedicated XAML namespace that supports XAML language constructs. This x: prefix is used for mapping this XAML namespace in the templates for projects, in examples, and in documentation throughout this SDK. The XAML namespace for the XAML language contain several programming constructs that you will use very frequently in your XAML. The following is a listing of the most common x: prefix programming constructs you will use: x:Key: Sets a unique key for each resource in a ResourceDictionary (or similar dictionary concepts in other frameworks). x:Key will probably account for 90% of the x: usages you will see in a typical WPF application's markup. x:Class: Specifies the CLR namespace and class name for the class that provides code-behind for a XAML page. You must have such a class to support code-behind per the WPF programming model, and therefore you almost always see x: mapped, even if there are no resources. x:Name: Specifies a run-time object name for the instance that exists in run-time code after an object element is processed. In general, you will frequently use a WPF-defined equivalent property for x:Name. Such properties map specifically to a CLR backing property and are thus more convenient for application programming, where you frequently use run time code to find the named elements from initialized XAML. The most common such property is FrameworkElement.Name. You might still use x:Name when the equivalent WPF framework-level Name property is not supported in a particular type. This occurs in certain animation scenarios. x:Static: Enables a reference that returns a static value that is not otherwise a XAML-compatible property. x:Type: Constructs a Type reference based on a type name. This is used to specify attributes that take Type, such as Style.TargetType, although frequently the property has native string-to-Type conversion in such a way that the x:Type markup extension usage is optional. There are additional programming constructs in the x: prefix/XAML namespace, which are not as common. For details, see XAML Namespace (x:) Language Features.

Custom Prefixes and Custom Types in XAML

For your own custom assemblies, or for assemblies outside the WPF core of PresentationCore, PresentationFramework and WindowsBase, you can specify the assembly as part of a custom xmlns mapping. You can then reference types from that assembly in your XAML, so long as that type is correctly implemented to support the XAML usages you are attempting. The following is a very basic example of how custom prefixes work in XAML markup. The prefix custom is defined in the root element tag, and mapped to a specific assembly that is packaged and available with the application. This assembly contains a

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

type NumericUpDown, which is implemented to support general XAML usage as well as using a class inheritance that permits its insertion at this particular point in a WPF XAML content model. An instance of this NumericUpDown control is declared as an object element, using the prefix so that a XAML parser knows which XAML namespace contains the type, and therefore where the backing assembly is that contains the type definition. Copy
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:custom="clr-namespace:NumericUpDownCustomControl;assembly=CustomLibrary" > <StackPanel Name="LayoutRoot"> <custom:NumericUpDown Name="numericCtrl1" Width="100" Height="60"/> ... </StackPanel> </Page>

For more information about custom types in XAML, see XAML and Custom Classes for WPF. For more information about how XML namespaces and the namespaces of the backing code in assemblies are related, see XAML Namespaces and Namespace Mapping for WPF XAML.

Events and XAML Code-Behind

Most WPF applications consist of both XAML markup and code-behind. Within a project, the XAML is written as a .xaml file, and a CLR language such as Microsoft Visual Basic or C# is used to write a code-behind file. When a XAML file is markup compiled as part of the WPF programming and application models, the location of the XAML code-behind file for a XAML file is identified by specifying a namespace and class as the x:Class attribute of the root element of the XAML. In the examples so far, you have seen several buttons, but none of these buttons had any logical behavior associated with them yet. The primary application-level mechanism for adding a behavior for an object element is to use an existing event of the element class, and to write a specific handler for that event that is invoked when that event is raised at run time. The event name and the name of the handler to use are specified in the markup, whereas the code that implements your handler is defined in the code-behind. XAML
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="ExampleNamespace.ExamplePage"> <Button Click="Button_Click" >Click Me!</Button> </Page>

Copy

VB

C#

C++

F#

JScript

Copy

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim b As Button = e.Source b.Foreground = Brushes.Red End Sub

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

Notice that the code-behind file uses the CLR namespace ExampleNamespace and declares ExamplePage as a partial class within that namespace. This parallels the x:Class attribute value of ExampleNamespace.ExamplePage that was provided in the markup root. The WPF markup compiler will create a partial class for any compiled XAML file, by deriving a class from the root element type. When you provide code-behind that also defines the same partial class, the resulting code is combined within the same namespace and class of the compiled application. For more information about requirements for code-behind programming in WPF, see the "Code-behind, Event Handler, and Partial Class Requirements" section of Code-Behind and XAML in WPF. If you do not want to create a separate code-behind file, you can also inline your code in a XAML file. However, inline code is a less versatile technique that has substantial limitations. For details, see Code-Behind and XAML in WPF.

Routed Events
A particular event feature that is fundamental to WPF is a routed event. Routed events enable an element to handle an event that was raised by a different element, as long as the elements are connected through a tree relationship. When specifying event handling with a XAML attribute, the routed event can be listened for and handled on any element, including elements that do not list that particular event in the class members table. This is accomplished by qualifying the event name attribute with the owning class name. For instance, the parent StackPanel in the ongoing StackPanel / Button example could register a handler for the child element button's Click event by specifying the attribute Button.Click on the StackPanel object element, with your handler name as the attribute value. For more information about how routed events work, see Routed Events Overview.

XAML Named Elements

By default, the object instance that is created in an object graph by processing a XAML object element does not possess a unique identifier or object reference. In contrast, if you call a constructor in code, you almost always use the constructor result to set a variable to the constructed instance, so that you can reference the instance later in your code. In order to provide standardized access to objects that were created through a markup definition, XAML defines the x:Name attribute. You can set the value of the x:Name attribute on any object element. In your code-behind, the identifier you choose is equivalent to an instance variable that refers to the constructed instance. In all respects, named elements function as if they were object instances (the name references that instance), and your code-behind can reference the named elements to handle run-time interactions within the application. This connection between instances and variables is accomplished by the WPF XAML markup compiler, and more specifically involve features and patterns such as InitializeComponent that will not be discussed in detail in this topic. WPF framework-level XAML elements inherit a Name property, which is equivalent to the XAML defined x:Name attribute. Certain other classes also provide property-level equivalents for x:Name, which is also generally defined as a Name property. Generally speaking, if you cannot find a Name property in the members table for your chosen element/type, use x:Name instead. The x:Name values will provide an identifier to a XAML element that can be used at run time, either by specific subsystems or by utility methods such as FindName. The following example sets Name on a StackPanel element. Then, a handler on a Button within that StackPanel references the StackPanel through its instance reference buttonContainer as set by Name. XAML
<StackPanel Name="buttonContainer">

Copy

...

<Button Click="RemoveThis">Click to remove this button</Button> </StackPanel>

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

VB

C#

C++

F#

JScript

Copy

Private Sub RemoveThis(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Dim fe As FrameworkElement = e.Source If (buttonContainer.Children.Contains(fe)) Then buttonContainer.Children.Remove(fe) End If End Sub

Just like a variable, the XAML name for an instance is governed by a concept of scope, so that names can be enforced to be unique within a certain scope that is predictable. The primary markup that defines a page denotes one unique XAML namescope, with the XAML namescope boundary being the root element of that page. However, other markup sources can interact with a page at run time, such as styles or templates within styles, and such markup sources often have their own XAML namescopes that do not necessarily connect with the XAML namescope of the page. For more information on x:Name and XAML namescopes, see Name, x:Name Directive, or WPF XAML Namescopes.

Attached Properties and Attached Events

XAML specifies a language feature that enables certain properties or events to be specified on any element, regardless of whether the property or event exists in the type's definitions for the element it is being set on. The properties version of this feature is called an attached property, the events version is called an attached event. Conceptually, you can think of attached properties and attached events as global members that can be set on any XAML element/object instance. However, that element/class or a larger infrastructure must support a backing property store for the attached values. Attached properties in XAML are typically used through attribute syntax. In attribute syntax, you specify an attached property in the form ownerType.propertyName. Superficially, this resembles a property element usage, but in this case the ownerType you specify is always a different type than the object element where the attached property is being set. ownerType is the type that provides the accessor methods that are required by a XAML processor in order to get or set the attached property value. The most common scenario for attached properties is to enable child elements to report a property value to their parent element. The following example illustrates the DockPanel.Dock attached property. The DockPanel class defines the accessors for DockPanel.Dock and therefore owns the attached property. The DockPanel class also includes logic that iterates its child elements and specifically checks each element for a set value of DockPanel.Dock. If a value is found, that value is used during layout to position the child elements. Use of the DockPanel.Dock attached property and this positioning capability is in fact the motivating scenario for the DockPanel class. XAML
<DockPanel> <Button DockPanel.Dock="Left" Width="100" Height="20">I am on the left</Button> <Button DockPanel.Dock="Right" Width="100" Height="20">I am on the right</Button> </DockPanel>

Copy

In WPF, most or all the attached properties are also implemented as dependency properties. For details, see Attached Properties Overview.
http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

Attached events use a similar ownerType.eventName form of attribute syntax. Just like the non-attached events, the attribute value for an attached event in XAML specifies the name of the handler method that is invoked when the event is handled on the element. Attached event usages in WPF XAML are less common. For more information, see Attached Events Overview.

Base Types and XAML

Underlying WPF XAML and its XAML namespace is a collection of types that correspond to CLR objects in addition to markup elements for XAML. However, not all classes can be mapped to elements. Abstract classes, such as ButtonBase, and certain nonabstract base classes are used for inheritance in the CLR objects model. Base classes, including abstract ones, are still important to XAML development because each of the concrete XAML elements inherits members from some base class in its hierarchy. Often these members include properties that can be set as attributes on the element, or events that can be handled. FrameworkElement is the concrete base UI class of WPF at the WPF framework level. When designing UI, you will use various shape, panel, decorator, or control classes, which all derive from FrameworkElement. A related base class, FrameworkContentElement, supports document-oriented elements that work well for a flow layout presentation, using APIs that deliberately mirror the APIs in FrameworkElement. The combination of attributes at the element level and a CLR object model provides you with a set of common properties that are settable on most concrete XAML elements, regardless of the specific XAML element and its underlying type.

XAML Security

XAML is a markup language that directly represents object instantiation and execution. Therefore, elements created in XAML have the same ability to interact with system resources (network access, file system IO, for example) as the equivalent generated code does. WPF supports the .NET Framework 4 security framework Code Access Security (CAS). This means that WPF content running in the internet zone has reduced execution permissions. "Loose XAML" (pages of noncompiled XAML interpreted at load time by a XAML viewer) and XAML browser application (XBAP) are usually run in this internet zone and use the same permission set. However, XAML loaded in to a fully trusted application has the same access to the system resources as the hosting application does. For more information, see WPF Partial Trust Security.

Loading XAML from Code

XAML can be used to define all of the UI, but it is sometimes also appropriate to define just a piece of the UI in XAML. This capability could be used to enable partial customization, local storage of information, using XAML to provide a business object, or a variety of possible scenarios. The key to these scenarios is the XamlReader class and its Load method. The input is a XAML file, and the output is an object that represents all of the run-time tree of objects that was created from that markup. You then can insert the object to be a property of another object that already exists in the application. So long as the property is an appropriate property in the content model that has eventual display capabilities and that will notify the execution engine that new content has been added into the application, you can modify a running application's contents very easily by loading in XAML. Note that this capability is generally only available in full-trust applications, because of the obvious security implications of loading files into applications as they run.

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

XAML Overview (WPF)

What's Next

This topic provides a basic introduction to XAML syntax concepts and terminology as it applies to WPF. For more information about the terms used here, see XAML Syntax In Detail. If you have not already done this, try the exercises in the tutorial topic Walkthrough: Getting Started with WPF. When you create the markup-centric application described by the tutorial, the exercise will help reinforce many of the concepts described in this topic. WPF uses a particular application model that is based on the Application class. For details, see Application Management Overview. Building a WPF Application (WPF) gives you more details about how to build XAML inclusive applications from the command line and with Microsoft Visual Studio. Dependency Properties Overview gives more information about the versatility of properties in WPF, and introduces the concept of dependency properties.

See Also

Concepts

XAML Syntax In Detail XAML and Custom Classes for WPF Base Elements Overview Trees in WPF
Other Resources

XAML Namespace (x:) Language Features WPF XAML Extensions

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/ms752059.aspx[6/18/2010 12:16:16 PM]

Designing with Windows Presentation Foundation

Home

Library

Learn

Downloads

Support

Community

Sign out | United States - English | Preferences

Designing with Windows Presentation Foundation


Follow the UX Guide Use Windows Presentation Foundation appropriately Guidelines Theming Software branding Custom controls 3-D Animations Dynamic behaviors Direct manipulation Hosting in browser Windows Presentation Foundation (WPF) is a user interface development environment that provides access to more advanced visuals, such as interfaces that incorporate documents, media, two- and three-dimensional graphics, animations, Web-like characteristics, and more. For a general overview, see Introducing Windows Presentation Foundation. When used appropriately, the WPF in Windows can help you create an engaging, productive experience your target users will love. If misused, it could lead to programs that are frustrating and difficult to use. The guidelines that follow will help you understand the difference, and use this technology appropriately.

Follow the UX Guide


While the Windows User Experience Guidelines (or "UX Guide") were written specifically for Windows, nearly all of these guidelines apply to programs using WPF as well. However, this shouldn't be a surprisethe primary goal of these guidelines is to establish a high-quality, consistent baseline for all Windows-based applications, no matter how they are implemented. While Windows Presentation Foundation gives you the flexibility to create a broad range of user experiencesfrom traditional Microsoft Windows to highly customizedyou should never feel that using WPF obligates you to abandon the Windows look and feel. In fact, WPF gives you the traditional Windows look and feel by default, and includes advanced versions of the Aero and Windows XP themes. Regardless of how your program looks, your WPF-based program can benefit from powerful capabilities such as a rich application model, dynamic layout, and data binding.

Use Windows Presentation Foundation appropriately


Among other things, WPF makes it possible to completely change your program's look to match your corporate branding, or to use a custom interaction model to give your program a "unique" feel. You can even customize a drop-down list to look like a slider! But when are such changes from a traditional experience genuinely appropriate?

What is "cool"?
WPF offers an exciting set of advanced capabilities. With this step forward comes the desire to create betteror "cooler" software. All too often these attempts don't seem to hit the mark. To understand why, let's make a distinction between what makes a program cool and what doesn't. A program really is "cool" when it has: Features appropriate for the program and its target users. Aesthetically pleasing look and feel, often in a subtle way. Improved usability and flow, without harming performance. A lasting good impressionit's just as enjoyable the 100th time as the first. A program fails to be "cool" when it has: Use or abuse of a technology just because it can. Features that detract from usability, flow, or performance.
http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

Is in the user's face, constantly drawing unnecessary attention to itself. A fleeting good impression. It might have been fun the first time, but the enjoyment wears off quickly. Just as in a painter's palette there are no intrinsically good or bad colors, there aren't intrinsically good or bad capabilities in WPF. Rather, for specific programs and their target users, we believe there are appropriate designs and inappropriate designs. Truly cool programs use technology because they should, not because they can. To achieve coolness, start not by thinking about what the technology can do, but by focusing on what your target users really need. Before adding that "cool" feature, make sure there are clear user scenarios that support it.

Target users
Designing great software boils down to a series of decisions about what functionality you present to the user and how it is presented. For great software, those decisions must be made based on the goals of the software and its intended audience. A good design decision must be made for the benefit of the target usersnever for yourself, or because the platform made it easy. To understand your target users, make a list of their knowledge, their goals, and their preferences. You should understand their motivation in using your program, how often they will use it, and their work environment. Also, consider creating user personas, which are fictitious people designed from real data, intended to represent classes of real users.

Program types
The type of program you are creating also factors into your decisions. Here are the characteristics of some common program types:
Productivity applications

Target users: Knowledge workers. Goals: Productivity, reduce costs. Usage: Used often for long periods of time, possibly all day. User expectation: Familiarity, consistency, immediate productivity. Appropriate use of WPF: Help users get their work done productively. Examples: Microsoft Office, line-of-business applications.
Consumer applications

Target users: Consumers. Goals: For users, perform a specific set of tasks. For ISVs, to sell well. Usage: Used occasionally (perhaps weekly) for short periods of time. User expectation: An enjoyable experience that performs targeted tasks well. Appropriate use of WPF: Help users perform tasks; some branding. Examples: Multimedia reference apps, media players and tools, security tools.
Games

Target users: Consumers. Goals: Entertainment. Usage: Used occasionally for moderate periods of time. User expectation: An immersive experience. Appropriate use of WPF: Custom look, possibly custom interaction. Examples: Simple games, online games.
Kiosks

Target users: Walkup users. Goals: Perform a specific task, get information. Usage: Once. User expectation: Perform task immediately, without learning anything. Appropriate use of WPF: Custom look, possibly custom interaction (touch, drag-and-drop), animations for visual explanations. Examples: Airport kiosks, museum kiosks.
IT Pro utilities

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

Target users: Developed and used by IT professionals. Goals: Perform a task or obtain information quickly. Usage: As needed, typically for short periods of time. User expectation: Get the job done. Appropriate use of WPF: Help IT pro develop and test UIs quickly.

Improving usability
Some design ideas are good simply because they improve usability. Here are some common ways to improve usability with WPF: Model the real world. You can use custom visuals and interactions to make specific controls look and behave like their real-world counterparts. This technique is best used when users are familiar with the real-world object, and the real-world approach is the best, most efficient way to perform the task. For example, simple utilities like calculators just work better when they model their real-world counterparts. Show instead of explain. You can use animations and transitions to show relationships, causes, and effects. This technique is best used to provide information that would otherwise require text to explain or might be missed by users. For example, a book for young children could animate page turns to show how the controls work. Normal page turns would be harder for a young child to understand. Improve affordance.Affordance is a property of an object that suggests how the object is used (as opposed to using a label to explain it). You can use custom control visuals and animations to suggest how nonstandard controls are used. Use natural mapping. Natural mapping is a clear relationship between what the user wants to do and how to do it. You can use custom appearances and interactions to create natural mappings when the standard common controls won't do. Reduce knowledge. You can use custom interactions to limit the number of ways to perform an operation and the amount of knowledge required to perform a task. Improve feedback. You can use custom control visuals and animations to give feedback to show that something is being done correctly or incorrectly, or to show progress. For example, the Address bar in Windows Internet Explorer shows the progress for loading the page in the background. Make objects easier to interact with. Fitts' law states that the effort required to click on a target is proportional to its distance and inversely proportional to its size. For example, you can use animations to make objects larger when the pointer is near and smaller when the pointer is far. Doing so makes the objects easier to click. It also allows you to use screen space more efficiently, by making objects normally smaller. Focus. You can use rich layout and custom visuals to emphasize screen elements that are crucial to the task, and to deemphasize secondary elements.

Making decisions
Now, let's put all these factors together. Should you use that transition effect idea you have for your program? Don't start by thinking about the fact that you can do it, or that it's really clever or easy to do. Those factors don't matter to your target users. Instead, consider the usability of the feature itself. Does the feature benefit from the transition, perhaps because it clarifies an object's source or destination? How quick is the transition? Would overall program performance be harmed? Consider your target users. Do they perform the task only occasionally and do their time constraints make that transition annoying? And finally, are such transitions appropriate for your program type? Simple transitions that aid in usability are appropriate for nearly all programs, whereas complex animations that don't aid in usability areat bestsuitable for programs intended to entertain users, such as games. By asking yourself the right questions and giving thoughtful answers, you can use the power of the WPF appropriately to create a great user experience.

The bottom line


At Microsoft, the four tenets of design are that software should be useful, usable, desirable, and feasible. We believe that this is the right list, and that it's in the right order. Appropriately applied, Windows Presentation Foundation helps you better satisfy all four of these tenets.

Guidelines
Theming

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

As a general rule, application theming is appropriate for programs where the overall experience is more important than productivity. Highly themed applications should be immersive, yet only used for short periods of time. This rule makes theming suitable for games and kiosk applications, but unsuitable for productivity applications. However, theming isn't an all-or-nothing deal. You can use customized control visuals for specific controls to give them a custom look. For branded consumer applications, you can use simple, subtle application theming to create a sense of brand. Do: Use the standard Windows theme for productivity applications. Consider using subtle, brand-related application theming for consumer applications. Games and kiosk applications may use heavy application theming to achieve an immersive experience. Theme selectively, subtly, and with restraint. Deciding to use a theme doesn't mean that you have to theme everything or make everything appear radically different. If your program models real-world objects, consider using custom visuals to make controls look and behave like those real-world objects, but only if that real-world approach offers the best, most efficient way to perform tasks. (This is a very high bar.) Consider using theming to emphasize screen elements that are crucial to the task, and de-emphasize elements that are secondary. Have professional graphic artists create your themes. Successful themes require an understanding of color, focus, contrast, texture, and use of dimension. Don't: Don't theme window non-client areas unless the application is an immersive experience, run at full screen with no other programs. When in doubt, don't theme.

Software branding
In a competitive marketplace, companies brand their products to help differentiate them from the competition. However, having your programs look and act weird doesn't make for a strong brand identity. Rather, your goal should be to create a program with charactera product that stands out while fitting in. Ultimately, users are most impressed by high quality programs that serve their purpose well. They are unlikely to be impressed by branding that is distracting, or harms usability or performance. Do: Choose good product names and logos, which are the foundation of your brand. Theming isn't. Consider having a link to your product's Web site from its About box and Help file. A product Web site is a far more effective way to sell your brand and support your product than branding within the product itself. If you must brand, consider low-impact branding: Small, subtle company or product logos, placed out of workflow. Small, subtle theme color changes that suggest your company or product colors. Don't: Don't use branding that is distracting or harms usability or performance. Don't use custom controls for branding. Rather, use custom controls when necessary to create a special immersive experience or when special functionality is needed. Don't use animated splash screens for branding. In fact, don't use any splash screens for programs that load quickly. Don't use animated logos. Don't plaster company or product logos on every UI surface. Limit product and company logos to at most two different surfaces, such as the main window or home page and the About box. Limit product and company logos to at most twice on any single surface. Limit product and company names to at most three times on any surface. For more guidelines and examples, see Branding.

Custom controls

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

The Windows common controls are familiar, consistent, flexible, and accessible. They require no learning from experienced Windows users and they are the right choice in almost all situations. That said, common controls work best for the usage patterns they were designed for. For example, before the slider control became standard, scroll bars were sometimes used instead. But scroll bars are intended for scrolling documents, not choosing from a continuous range of values. Before the standard slider control, it was a good idea to use a custom control for this interaction. Do: Use custom controls for unusual behaviors that aren't supported by the common controls. Ensure custom controls support system metrics and colors and respect all user changes to these settings. Ensure custom controls conform to the Windows accessibility guidelines. Don't: Don't assign nonstandard behaviors to the common controls. Use standard behaviors if you can, and custom controls only if you must. Don't underestimate the work required to use custom controls correctly.

3-D
Do: Use 3-D graphics to help users visualize, examine, and interact with three-dimensional objects, charts, and graphics. Make sure there are clear user scenarios that support the need for 3-D graphics features. Don't: Don't use 3-D graphics just because you can.

Animations
There are five basic types of animations: Illustration animations communicate information visually instead of verbally. Effect animations create interactions to model their real-world counterparts. Relationship animations show relationships between objects (where objects come from, went to). Transition animations show major UI state changes. Feedback animations show that something is being done correctly or incorrectly, or show processing progress. The human eye is sensitive to motion, especially peripheral motion. If you use animation to draw attention to something, make sure that attention is well deserved and worthy of interrupting the user's train of thought. Animations don't have to demand attention to be successful. In fact, many successful animations are so natural that users aren't even aware of them. Do: Illustration animations Use illustration animations that have a single interpretation. They have little value if confusing. Show one thing at a time to avoid overwhelming users. Play at the optimal speednot so fast they are difficult to understand, but not so slow they are tedious to watch. Gradually increase the speed of repeated animations. Viewers will already be familiar with the animation, so increasing speed slowly will feel right. Use timing to emphasize importance, such as slowing down for important parts. Effect animations Use effect animations for objects that the user is currently interacting with. Such animations aren't distracting because the user is already focused on the object. Minimize use of effect animations that show status. Make sure:

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

They have real value by providing additional information users can actually use. Examples include transient status changes and emergencies. They are subtle. They are short in duration and therefore not running most of the time. They can be turned off. Keep effect animations low-key so they don't draw too much attention to themselves. Avoid movement or use small movements, but prefer fades and changes in overlays. Relationship animations Must start or end with the selected object. Don't show relationships between objects the user isn't currently interacting with. Must complete within a half-second or less. Transition animations Use to show relationships between states. Animating state changes makes them easier to understand and appear smoother. Make sure transitions have natural mappings. For example, an opening window transition should be upward and expand; a closing window transition should be downward and contract. Must complete within a half-second or less. Feedback animations Must have clearly identifiable completion and failure states. Must stop showing progress when the underlying process isn't making progress. Don't: Don't use animations that affect performance noticeably. Consider performance over slow network connections or when many objects are involved. Don't draw attention to things that aren't worthy of attention.

Dynamic behaviors
With WPF, you can use progressive disclosure to show or hide additional information. Progressive disclosure promotes simplicity by focusing on the essential, yet revealing additional detail as needed. Progressive disclosure controls are usually displayed without direct labels that describe their behavior, so users must be able to do the following based solely on the control's appearance: Recognize that the control provides progressive disclosure. Determine if the current state is expanded or collapsed. Determine if additional information, options, or commands are needed to perform the task. Determine how to restore the original state, if desired. While users can determine the above by trial and error, try to make such experimentation unnecessary. Do: Make sure the progressive disclosure mechanism is visible at all times. Use the appropriate glyph. Use double or single chevrons for surfaces that slide open to show the remaining items in hidden content. Point the glyph in the right direction. Chevrons point in the direction where the action will occur. Don't: Don't depend upon mouse hover effects to reveal progressive disclosure.

Direct manipulation
With WPF, you can use direct manipulation to let users interact directly with objects using their mouse, instead of indirectly with the keyboard, dialog boxes, or menus.

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

Designing with Windows Presentation Foundation

Direct manipulation is a natural way to perform many tasks. It is easy to learn, and convenient to use. But there are many challenges, the most important being to prevent accidental manipulation of important data. Do: Make direct manipulation visible by: Changing the pointer to a hand on mouseover. Showing drag handles on object selection. Showing movement when an object is dragged, then show appropriate drop targets. Also, clearly show when an object is successfully dropped or when the drop is cancelled. Showing an in-place text box on double selection for renaming. Showing most useful properties with tooltips. Prevent accidental manipulation by: Locking by default objects that are crucial or likely to be manipulated accidentally. Provide a way to unlock in the object's context menu. Providing an obvious way to undo accidental manipulations. Make direct manipulation accessible by always providing alternatives. Don't: Don't overuse direct manipulation by providing it where there is very little value. Overuse can lead to a UI so fragile that users are reluctant to interact with it.

Hosting in browser
You have the option of hosting your WPF-based program in a browser. Do: Host your program in the browser to navigate from a Web page to your program. Don't: Don't host your program in the browser when: It is used to edit rich content (for example, a word processor). It requires multiple windows. It is a background task that would be broken or interrupted if users were to navigate away (for example, a media player).

2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Feedback

http://msdn.microsoft.com/en-us/library/Aa511329[6/18/2010 12:17:19 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

7,127,766 members and growing! (17,867 online)

Email

Password

Sign in

Join

Join

Remember me?

Lost your password?

Home

Articles

Quick Answers

Message Boards

Job Board

Catalog

Help!
XAML, WPF, Silverlight

Lounge

Platforms, Frameworks & Libraries Windows Presentation Foundation General License (CPOL)

License: The Code Project Open

21 Important FAQ questions for WPF and SilverLight


By Shivprasad koirala 21 Important FAQ questions for WPF and SilverLight

Revision: 9 (See All) Posted: 24 Mar 2009 Updated: 8 Oct 2009 Views: 37,566 Bookmarked: 132 times Unedited contribution
Articles / Quick Answers Articles / Quick Answers
Go!

Announcements
Write an iPhone Tutorial, Win an iPad Local Government Windows Azure Competition Monthly Competition Print Friendly Share

Search
Discuss Report

Advanced Search Add to IE Search

57 votes for this article. Popularity: 8.36 Rating: 4.76 out of 5


1 2 3 4 5

The Daily Insider


23 Things Not To Write In An E-mail Daily IT news: Signup now.

Updated links of LINQ FAQ Part 1, Part2, Part3 & One-Many and One-One relationship using LINQ to SQL are moved to bottom of the article.

21 Important FAQ questions for WPF and SilverLight


Introduction What is the need of WPF when we had GDI, GDI+ and DirectX? How does hardware acceleration work with WPF? Does that mean WPF has replaced DirectX? So can we define WPF in a precise way? What is XAML? So is XAML meant only for WPF ? Can you explain the overall architecture of WPF? Which are the different namespaces and classes in WPF ? Can explain the different elements involved in WPF application practically? What are dependency properties? Are XAML file compiled or built on runtime? Can you explain how we can separate code and XAML? How can we access XAML objects in behind code? What kind of documents are supported in WPF? What is SilverLight ?

Wanted
(LAMP) Software Engineer at Adknowledge View this and other fine jobs on the Job Board.

Articles
Desktop Development Web Development Mobile Development Enterprise Systems Database Multimedia Languages Platforms, Frameworks & Libraries ATL MFC STL WTL COM / COM+ .NET Framework Win32/64 SDK & OS Vista API Vista Security Cross Platform Game Development Mobile Development Windows CardSpace Windows Communication Foundation Windows Presentation Foundation Windows Workflow Foundation

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject


Libraries Windows Powershell LINQ Azure General Programming Graphics / Design Development Lifecycle General Reading Third Party Products Mentor Resources

Come on, even WPF runs under browser why SilverLight ? Can SilverLight run in other platforms other than window? What is the relationship between Silver Light, WPF and XAML? Can you explain SilverLight architecture? Source code Other silverlight FAQ

Services
Product Catalog Job Board CodeProject VS2008 Addin

Feature Zones
Product Showcase WhitePapers / Webcasts .NET Dev Library ASP.NET 4 Web Hosting

Introduction
This article talks about 21 important FAQ from the perspective of WPF and Silver light. Both of these technologies are connected to a certain extent. This article not only explains the theory aspect of these technologies but also shows small samples for each of them. Heres a complete free e-book covering 400 FAQ for C#, SQL Server, WPF, WWF, WCF and lot more feel free to download it and enjoy http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip

What is the need of WPF when we had GDI, GDI+ and DirectX?

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

First lets try to understand how display technology has evolved in Microsoft technology. User32:- This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities. GDI (Graphics device interface):- Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. GDI+:- GDI+ was introduced which basically extends GDI and provides extra functionalities like JPG and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Note: - Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU. DirectX :- One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more. This API no matured when it comes to gaming industry. WPF :- Microsoft almost had 3 to 4 API's for display technologies , so why a need for one more display technology. DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX. So lets define WPF.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

WPF is a collection of classes that simplify building dynamic user interfaces. Those classes include a new set of controls, some of which mimic old UI elements (such as Label, TextBox, Button), and some that are new (such as Grid, FlowDocument and Ellipse).

How does hardware acceleration work with WPF?


Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU. WPF exploits hardware acceleration in a two tier manner.

WPF API first detects the level of hardware acceleration using parameters like RAM of video card , per pixel value etc. Depending on that it either uses Tier 0, Tier 1 or Tier 2 rendering mode. Tier 0:- If the video card does not support hardware acceleration then WPF uses Tier 0 rendering mode. In other words it uses software acceleration. This corresponds to working of DirectX version less than 7.0. Tier 1:- If the video card supports partial hardware acceleration then WPF uses Tier 1 rendering mode. This corresponds to working of DirectX version between 7.0 and 9.0. Tier 2:- If the video card supports hardware acceleration then WPF uses Tier 2 rendering mode. This corresponds to working of DirectX version equal or greater than 9.0.

Does that mean WPF has replaced DirectX?


No, WPF does not replace DirectX. DirectX will still be still needed to make cutting edge games. The video performance of directX is still many times higher than WPF API. So when it comes to game development the preference will be always DirectX and not WPF. WPF is not a optimum solution to make games, oh yes you can make a TIC TAC TOE game but not high action animation games. One point to remember WPF is a replacement for windows form and not directX.

So can we define WPF in a precise way?


Windows Presentation Framework is the new presentation API. WPF is a two and three dimensional graphics engine. It has the following capabilities: Has all equivalent common user controls like buttons, check boxes sliders etc. Fixed and flow format documents Has all of the capabilities of HTML and Flash 2D and 3D vector graphics Animation Multimedia Data binding

What is XAML?

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set their properties. XAML describes objects, properties and there relation in between them. Using XAML, you can create any kind of objects that means graphical or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relation as defined by XAML. So XAML is a XML document which defines objects and properties and WPF loads this document in actual memory.

So is XAML meant only for WPF ?


No,XAML is not meant only for WPF.XAML is a XML-based language and it had various variants. WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents. Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us to create rich web content with 2-dimensional graphics, animation, and audio and video. WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.

Can you explain the overall architecture of WPF?

Above figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore. In the same diagram we have shown how other section like direct and operating system interact with the system. So lets go section by section to understand how every section works. User32:- It decides which goes where on the screen. DirectX: - As said previously WPF uses directX internally. DirectX talks with drivers and renders the content. Milcore: - Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. Presentation core ;- This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc. Presentation framework:- This section has high level features like application controls , layouts . Content etc which helps you to build up your application.

Which are the different namespaces and classes in WPF ?

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

There are ten important namespaces / classes in WPF. System.Threading.DispatcherObject All WPF objects derive from the DispatcherObject. WPF works on STA model i.e. Single Threading Apartment Model. The main duty of this object is to handle concurrency and threading. When any message like mouse clicks, button clicks etc are initiated they are sent to the DispatcherObject who verifies whether code is running on the correct thread. In the coming section we will look in to detail how WPF threading works. System.Windows.DependencyObject When WPF was designed property based architecture was considered. In other words rather than using methods, functions and events object behavior will interact using properties. For now we will only restrict ourselves to this definition. In the coming section we have dedicated question for the same. System.Windows.Media.Visual Visual class is a drawing object which abstracts drawing instructions, how drawing should be drawn like clipping, opacity and other functionalities. Visual class also acts like a bridge between unmanaged MilCore.dll and WPF managed classes. When any class derived from visual it can be displayed on windows. If you want to create your own customized user interface then you can program using visual objects.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

System.Windows.UIElement UIElement handled three important aspects layout, input and events. System.Windows.FrameworkElement FrameWorkElement uses the foundation set by UIElement. It adds key properties like HorizontalAlignment , VerticalAlignment , margins etc. System.Windows.Shapes.Shape This class helps us to create basic shapes such as Rectangle, Polygon, Ellipse, Line, and Path. System.Windows.Controls.Control This class has controls like TextBox,Button,ListBox etc. It adds some extra properties like font,foreground and background colors. System.Windows.Controls.ContentControl It holds a single piece of content. This can start from a simple label and go down to a unit level of string in a layout panel using shapes. System.Windows.Controls.ItemsControl This is the base class for all controls that show a collection of items, such as the ListBox and TreeView. System.Windows.Controls.Panel This class is used for all layout containerselements that can contain one or more children and arrange them as per specific layout rules. These containers are the foundation of the WPF layout system, and using them is the key to arranging your content in the most attractive, flexible way possible.

Can explain the different elements involved in WPF application practically?


In order to understand the different elements of WPF, we will do a small hello world sample and in that process we will understand the different elements of WPF. Note :- For this sample we have VS 2008 express edition. So start VS 2008 express and from the templates select the WPF application as show in the below figure below.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

Once we have created the WPF application project you will see two file types one the XAML file and the other is the behind code i.e. XAML.cs. XAML files are nothing but XML files which has all the elements needed to display the windows UI. Every of the XAML elements maps to come class. For instance the Window element maps to WpfApplication1.Window1 class , Button elements in XAML file maps to System.Windows.Control.Button class and Grid XAML element is mapped to System.Windows.Control.Grid.

The App.XAML and App.XAML.CS are the entry point files. If we see the code for App.XAML.CS you will see the reference to XAML file which needs to be loaded. So the first code which runs in the application is void main() method from App.XAML.CS which in turn loads the Window1.XAML file for rendering.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

We can now connect the behind code method and function to events in XAML file elements.

You can see from the above code snippet how the button element has the click event linked to the MyButton_Click function. MyButton_Click is the method which is in the XAML.CS behind code. So now if you run the code you can see the button and if you click on it you can see the message box for the same.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

What are dependency properties?


These dependency properties belong to one class but can be used in another. Consider the below code snippet:Collapse Collapse Copy Code

<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" />

Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas.

Are XAML file compiled or built on runtime?


XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runtime. When we build a XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for every XAMl file you will find a g.cs file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short, in runtime you actually do not see the XAML file. But if you want to do runtime, parsing of XAML file it also allows that to be done.

Can you explain how we can separate code and XAML?


This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.

Figure 16.1:- XAML and behind code in action Above is the code snippet, which shows a XAML file and the code completely detached from the XAML presentation. In order to associate a class with XAML file you need to specify the x: Class attribute. Any event specified on the XAML object can be connected by defining a method with sender and event values. You can see from the above code snippet we have linked the MyClickEvent to an event in the behind code. Note: - You can get a simple sample in WindowsSimpleXAML folder. Feel free to experiment with the code experimenting will teach you much more than reading something theoretical.

How can we access XAML objects in behind code?


To access XAML objects in behind code you just need to define them with the same name as given in the XAML

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

document. For instance in the below code snippet we named the object as objtext and the object is defined with the same name in the behind code.

Figure 16.2 Accessing XAML object Note: - You can get the source code in WindowsAccessXAML folder.

What is SilverLight ?
Silver light is a web browser plug-in by which we can enable animations, graphics and audio video. You can compare silver light with flash. We can view animations with flash and its installed as a plug-in in the browser.

Can SilverLight run in other platforms other than window?


Yes, animations made in SilverLight can run in other platforms other than window. In whatever platform you want run you just need the SilverLight plug-in.

Come on, even WPF runs under browser why SilverLight ?


Yes there is something called as WPF browser application which can run WPF in browser. For WPF browser application you need .Net framework to be installed in the client location while for silver light you need only the plug-in. So in other words WPF browser applications are OS dependent while SilverLight is not. SilverLight plugin can run in other OS other than windows while we all know .NET framework only runs in windows.

What is the relationship between Silver Light, WPF and XAML?


As explained previously XAML is a XML file which defines the UI elements. This XML file can be read by WPF framework or Silver light framework for rendering. Microsoft first developed WPF and they used XAML files to describe the UI elements to the WPF framework. Microsoft then extended WPF and made WPF/e which helped to render the UI in the browser. WPF/e was the code name for Silver Light. Later Microsoft launched Silver Light officially. So the XAML just defines the XML structure to represent the UI elements. Both the frameworks i.e. WPF and Silverlight then reads the UI elements and renders the UI elements in the respective platform.

Can you explain SilverLight architecture?


Before we talk about silver light architecture lets discuss what is silver light is really made of technically. Silver light has borrowed lot of things from existing Microsoft technologies. We can think silver light plug-in as a

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

combination of some technologies from core .NET framework, vector animations, media and JavaScript.

So we can visualize the silver light architecture as combination of some functionalities from core .NET framework , Ajax and some functionalities like animation , media etc provided by core silver light framework. We can think silver light architecture as a combination of four important blocks: Some .NET framework components: - Silver light uses some components from .NET framework. One of the main components is WPF. Many of the UI components ( check box , buttons , text boxes etc) , XAML parsing etc are taken from the core WPF system. It also has taken components like WCF to simplify data access. It also have CLR for memory management, safety checking and garbage collection. The base class libraries of Net are used for string manipulations, algorithms, expressions, collections and globalization. Presentation core: - The core presentation framework has functionalities to display vector 2d animations, images, media, DRM and handle inputs like mouse and keyboard. Other technologies: - Silver light interacts with other technologies like Ajax and javascript. So it also borrows some functionalities from there technologies. Hosting: - Silver light animations finally run under the browser environment. So it has a the hosting functionality which helps to host the application the browser , expose a DOM by which JavaScript can manipulate the silver light components and it also has a installer functionality which helps to install silver light application and plug-in in the browser environment. One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. The XAML is a component which is a part of the .NET framework and the rendering part is done by the presentation core.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

The application is a typical HTML which runs under the browser. There are markups which instantiates the silver light plug-in. Now when user interacts with the silver light application it sends event to JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript of .NET can make calls to the silver light run-time and achieve the necessary functionalities. XAML will be read and parsed by the silver light runtime and then rendered accordingly to the browser.

What are the various basic steps to make a simple Silver Light application? This sample we are making using VS 2008 web express edition and .NET 3.5. Its a 6 step procedure to run our first silver light application. So lets go through it step by step. Step1:- The first thing we need to do is install silverlight SDK kit from http://www.microsoft.com/downloads/details.aspx?familyid=FB7900DB-4380-4B0F-BB950BAEC714EE17&displaylang=en Step 2:- Once you install the silver light SDK you should be able to use the silver light template. So when you go to create a new project you will see a SilverLight application template as shown in the below figure.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

Step 3 :- Once you click ok you will see a dialog box as shown below which has three options.

Add a ASP.NET web project to the solution to host silver light: - This option is the default option, and it will create a new Web application project that is configured to host and run your Silverlight application. If you are creating a new silver light application then this is the option to go. Automatically generate Test Page To Host Silverlight at build time: - This option will create a new page at run time every time you try to debug and test your application. If you want to only concentrate on your silver light application then this option is worth looking at. Link This Silverlight Control Into An Existing Web Site :- If you have a existing silver light application then this option helps to link the silver light application with the existing web application project. You will not see this option enabled to new projects , you need to have an existing web application. For this example we have selected the first option. Once you click ok you should see the full IDE environment for silver light.

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

So lets run through some basic points regarding the IDE view what we see. You will see there are two projects one is your web application and the other is the silver light application. In the silver light application we two XAML files one is App.XAML and the other is Page.XAML. App.XAML has the global level information. Step 4:- Now for simplicity sake we just use the TextBlock tag to display a text. You can see as we type in the Page.XAML its displayed in the viewer.

Step 5 :- Now we need to consume the silver light application in a ASPX page. So in the HTML / ASPX page we need to first refer the silver light name space using the Register attribute.
Collapse Collapse Copy Code

<%@Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

We also need to refer the script manager from the silver light name space. The script manager control is functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.
Collapse Collapse Copy Code

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

Finally we need to refer the silver light application. You can see that in the source we have referred to the XAP file. XAP file is nothing but a compiled silver light application which is compressed and ZIP. It basically has all the files thats needed for the application in a compressed format. If you rename the file to ZIP extension you can open the same using WINZIP.
Collapse Collapse Copy Code

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MyFirstSilverLightApplication.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

So your final ASPX / HTML code consuming the silver light application looks something as shown below.
Collapse Collapse Copy Code

<%@ Page Language="C#" AutoEventWireup="true" %> <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;"> <head runat="server"> <title>MyFirstSilverLightApplication</title> </head> <body style="height:100%;margin:0;"> <form id="form1" runat="server" style="height:100%;"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <div style="height:100%;"> <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MyFirstSilverLightApplication.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" /> </div> </form> </body> </html>

Step 6 :- So finally set the web application as start up and also set this page as start up and run it. You should be pleased to see your first silver light application running.

Source code
You can download the source code Click here

Other SilverLight FAQ


LINQ FAQ Part 1 :- http://www.codeproject.com/KB/linq/LINQNewbie.aspx Silverlight FAQ Part2: - SilverLight FAQ's - Part2 Silverlight FAQ Part3: - SilverLight FAQ's - Part3 One-Many and One-One relationship using LINQ to SQL: - One-Many and One-One relationship using LINQ to SQL

License
This article, along with any associated source code and files, is licensed under The Code Project Open License

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

(CPOL)

About the Author


Shivprasad koirala I am a Microsoft MVP for ASP/ASP.NEt and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at http://www.questpond.com and also enjoy the videos uploaded for Design pattern, FPA , UML ,Share Point,WCF,WPF,WWF,LINQ, Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Occupation: Architect Company: Location: http://www.questpond.com India

Member

Article Top

Sign Up to vote for this article

You must Sign In to use this message board. FAQ Noise Tolerance
Medium Medium
Search

Layout

Normal Normal

Per page

25 25

Update

Msgs 1 to 13 of 13 (Total in Forum: 13) (Refresh) Nice article Great Article but is the example of dependency property right? Simply Superb! Member 4178170 akjoshi Arfan Baig

First Prev Next 0:48 27 May '10 3:40 24 Mar '10 22:19 18 Mar '10

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

21 Important FAQ questions for WPF and SilverLight - CodeProject

Very Nice Really Nice Excellent Nice format! However... Nice! What is WPF namespace? good pictorial representation Nice Stuff Very nicely Explained koirala Very Very Nice Last Visit: 21:49 17 Jun '10 General News Last Update: 21:49 17 Jun '10 Question Answer Joke Rant Admin

gaoyuegl Sathishkumar_P Cybernate TheArchitectualizer prasad02 o3yoon vikas amin wasimsharp kamii47 dishatera

22:51 12 Sep '09 3:05 24 Aug '09 9:40 2 Jul '09 3:35 30 Jun '09 20:50 1 Jun '09 20:02 10 Apr '09 10:39 7 Apr '09 20:02 30 Mar '09 5:06 25 Mar '09 5:32 24 Mar '09 1

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.
PermaLink | Privacy | Terms of Use Last Updated: 8 Oct 2009 Editor: Sean Ewington Copyright 2009 by Shivprasad koirala Everything else Copyright CodeProject, 1999- 2010 Web22 | Advertise on the Code Project

http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx[6/18/2010 12:19:52 PM]

Vous aimerez peut-être aussi