0% found this document useful (0 votes)
43 views

XML Developer Reference Free Sampler

Microsoft Press Ebooks offers lifetime access to ebooks purchased through oreilly.com in multiple DRM-free formats. The document outlines the features of these ebooks, including searchability, cut-and-paste functionality, and updates for corrections. It also provides information on purchasing options and copyright details for the content.

Uploaded by

D M Bok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

XML Developer Reference Free Sampler

Microsoft Press Ebooks offers lifetime access to ebooks purchased through oreilly.com in multiple DRM-free formats. The document outlines the features of these ebooks, including searchability, cut-and-paste functionality, and updates for corrections. It also provides information on purchasing options and copyright details for the content.

Uploaded by

D M Bok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Microsoft Press Ebooks—Your bookshelf on your devices!

When you buy an ebook through oreilly.com you get lifetime access to the book, and
whenever possible we provide it to you in five, DRM-free file formats—PDF, .epub,
Kindle-compatible .mobi, Android .apk, and DAISY—that you can use on the devices of
your choice. Our ebook files are fully searchable, and you can cut-and-paste and print
them. We also alert you when we’ve updated the files with corrections and additions.

Learn more at ebooks.oreilly.com


You can also purchase O’Reilly ebooks through the iBookstore,
the Android Marketplace, and Amazon.com.

Spreading the knowledge of innovators oreilly.com


Published with the authorization of Microsoft Corporation by:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, California 95472

Copyright © 2011 by Mamta Dalal and Ashish Ghoda


All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any
means without the written permission of the publisher.

ISBN: 978-0-7356-5896-7

1 2 3 4 5 6 7 8 9 LSI 6 5 4 3 2 1

Printed and bound in the United States of America.

Microsoft Press books are available through booksellers and distributors worldwide. If you need support related
to this book, email Microsoft Press Book Support at [email protected]. Please tell us what you think of
this book at http://www.microsoft.com/learning/booksurvey.

Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/


Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other marks are property of
their respective owners.

The example companies, organizations, products, domain names, email addresses, logos, people, places, and
events depicted herein are fictitious. No association with any real company, organization, product, domain name,
email address, logo, person, place, or event is intended or should be inferred.

This book expresses the author’s views and opinions. The information contained in this book is provided without
any express, statutory, or implied warranties. Neither the authors, O’Reilly Media, Inc., Microsoft Corporation,
nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly
or indirectly by this book.

Acquistions and Developmental Editor: Russell Jones


Production Editor: Kristen Borg
Editorial Production: S4Carlisle Publishing Services
Technical Reviewer: Vikas Sahni
Copyeditor: Becka McKay
Indexer: Denise Getz
Cover Design: Twist Creative • Seattle
Cover Composition: Karen Montgomery
Illustrator: S4Carlisle Publishing Services
Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Part I XAML Basics

Chapter 1 Introducing XAML 3


Windows Presentation Foundation (WPF). . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

XAML—A Declarative Language for .NET Applications. . . . . . . . . . . . . . . . . 4


XAML Is Part of the Microsoft Open Specification Program (OSP). . 6
XAML Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Dynamic User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Decouple Control Style Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Customized Design of XAML Controls. . . . . . . . . . . . . . . . . . . . . . . . . . 9
Integration with Code-Behind to Control Behavior. . . . . . . . . . . . . . . 9
Inline Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Silverlight. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

The Microsoft .NET Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14


Design-Time Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Runtime Cross-Platform Components. . . . . . . . . . . . . . . . . . . . . . . . . 16

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

What do you think of this book? We want to hear from you!


Microsoft is interested in hearing your feedback so we can continually improve our
books and learning resources for you. To participate in a brief online survey, please visit:

microsoft.com/learning/booksurvey

vii

Chapter 2 Object Elements and Attributes 19
XAML Is XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Root Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
XAML Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Default User Interface Element. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Introducing the XAML Presentation Framework . . . . . . . . . . . . . . . . . . . . . 28


WPF and Silverlight Presentation Framework. . . . . . . . . . . . . . . . . . . 28
Defining User Interfaces with XAML. . . . . . . . . . . . . . . . . . . . . . . . . . . 30

XAML User Interface Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41


Layout and Positioning Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Form Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Functional Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Data Handling and Information Management Controls. . . . . . . . . . 45
Image and Media Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Graphics and Animation Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Chapter 3 XAML Properties and Events 49


XAML Properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

XAML Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
The Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
The EventSetter and EventTrigger Classes. . . . . . . . . . . . . . . . . . . . . . . 81

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83

Part II Enhancing User Experience

Chapter 4 Markup Extensions and Other Features 87


Markup Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

Built-In XAML Markup Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

XAML Markup Extensions Used in WPF and Silverlight. . . . . . . . . . . . . . . . 94

Escape Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Custom Markup Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

viii Contents
Type Converters versus Markup Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . 98

XAML Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Security in XAML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100

Chapter 5 Resources, Styles, and Triggers 101


Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Types of Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102


Static Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Defining Static Resources Using XAML . . . . . . . . . . . . . . . . . . . . . . . 102
Defining Static Resources Programmatically. . . . . . . . . . . . . . . . . . . 104
Dynamic Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
When to Use Which Resource. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
How Static and Dynamic Resources Work. . . . . . . . . . . . . . . . . . . . . 106

Defining ResourceDictionary Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Merged Resource Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Scope and Hierarchy of Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Defining Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Implicit Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Inheriting Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
The Silverlight Toolkit Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Styles vs. Control Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
More on Styles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
The generic.xaml File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Triggers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

Troubleshooting Resources, Styles, and Triggers . . . . . . . . . . . . . . . . . . . . 126

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126

ix

Part III XAML User Interface Controls

Chapter 6 Layout and Positioning System 129


The Layout System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

XAML Layout and Positioning Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Common Sizing and Positioning Properties. . . . . . . . . . . . . . . . . . . . . . . . .160

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170

Chapter 7 Form and Functional Controls 171


Action Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
The ButtonBase Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

Text Editing Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182


The TextBoxBase Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

Functional Controls to Improve Usability. . . . . . . . . . . . . . . . . . . . . . . . . . . 194

Functional Controls to Control and Monitor Behavior. . . . . . . . . . . . . . . . 205


The RangeBase Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .210

Part IV Content Integration and Animation

Chapter 8 Data Binding 213


Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Data Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215


Setting the Binding Source. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
MultiBinding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Binding to Data from a Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

Binding Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227


Example of Two-Way Binding with TextBox. . . . . . . . . . . . . . . . . . . . 227
Source Updates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228

Data Templating, Conversion, and Validation. . . . . . . . . . . . . . . . . . . . . . . 228


Data Templating. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Data Conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Data Validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

x Contents
Creating and Binding to an ObservableCollection. . . . . . . . . . . . . . . . . . . . 234

Collection Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235


Sorting and Grouping Using a CollectionView . . . . . . . . . . . . . . . . . 235

Hierarchical Binding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238


Using HierarchicalDataTemplate. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Using ObservableCollection for Hierarchical Binding. . . . . . . . . . . . 241

Binding to XML Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .244

Chapter 9 Media, Graphics, and Animation 245


Media . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Images. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Audio and Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Ellipse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Rectangle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Rounded Rectangle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Polygon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Polyline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Geometries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Brushes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Transforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

3-D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261


3-D Graphics in WPF. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261
Defining Shapes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
3-D Graphics in Silverlight. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Pixel Shaders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

Animations and Storyboards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285

Contents xi
Part V Appendixes

Appendix A Major Namespaces and Classes 289


Commonly Used Namespaces and Classes in WPF. . . . . . . . . . . . . 289
Commonly Used Namespaces and Classes in Silverlight . . . . . . . . 293

Appendix B XAML Editors and Tools 299


Editors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Kaxaml. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
XAML Cruncher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
XamlPad. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
XamlPadX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

Index 303

What do you think of this book? We want to hear from you!


Microsoft is interested in hearing your feedback so we can continually improve our
books and learning resources for you. To participate in a brief online survey, please visit:

microsoft.com/learning/booksurvey

xii Contents
C h apter 1

Introducing XAML

In this chapter:
■■ Windows Presentation Foundation (WPF)

■■ XAML—A Declarative Language for .NET Applications

■■ Silverlight

■■ The Microsoft .NET Framework

■■ Summary

Object-oriented and service-oriented programming models (along with language- and


­environment-independent features) lie at the core of the .NET Framework architecture. Since the
release of .NET Framework 3.0, Microsoft has added several important components to support the
unified programming and deployment model:

■■ A presentation layer Windows Presentation Foundation (WPF)

■■ A messaging and communication services layer Windows Communication Foundation


(WCF)

■■ Workflow management Windows Workflow Foundation (WF)

You use the Windows Presentation Foundation (WPF) framework libraries along with the
­ ML-based eXtensible Application Markup Language (XAML) declarative markup language to define
X
and develop next-generation, abstracted, dynamic, rich, and interactive user interface layers that
provide data-integration capabilities and comprehensive support for multimedia, graphics, animation,
and documents.

The eXtensible Application Markup Language (XAML, pronounced zammel)—a declarative


­ ML-based markup language—is at the center of the declarative user interface (UI) WPF framework.
X
It is a language for describing an abstracted—externalized and decoupled—user interface layer. The
current .NET Framework has extended XAML as its core user interface definition language to define
user interfaces not only for WPF and Silverlight applications, but also for the custom activity libraries
of WF 4.0–based workflows.

3

Windows Presentation Foundation (WPF)
WPF supports the development of rich and interactive Windows desktop applications that can pro-
vide sophisticated and realistic user experiences. WPF is built upon a very different architecture than
­Windows Forms. The key architectural differences are:

■■ WPF introduces a new user interface XML-based declarative markup language—XAML—


that can support layout, styles, resources, and control templates to simplify and standardize
­management of the visual appearance of the user interface. XAML also supports properties
and events that developers can handle in code-behind code to control its behavior.

■■ WPF provides a new presentation framework that integrates XAML for user interface design.
The framework supports a unified programming model that includes data binding capabilities
to develop data-driven applications as well as media integration, 2-D and 3-D vector graphics,
document integration, text, and typography.

■■ WPF provides a set of .NET Framework libraries for the presentation core that are mainly
derived from the System.Windows namespace. These libraries handle integration of the
­X AML-based user interface with the managed code-behind, including enhanced properties
and events integration, such as dependency properties and routed events (topics you’ll explore
later in this book).

■■ The new Media Integration Layer (MIL) provides a rendering engine for WPF applications built
upon Direct3D. The tight integration with DirectX means that WPF has high-performance
rendering of the visual interface that can take advantage of hardware acceleration using
the graphics processing units (GPUs) that most modern computers have, which reduces the
load on the central processing unit (CPU). This is a very different approach than that taken
in ­Window Forms applications, where the .NET Framework uses the User32 DLL to render
­standard Window Forms user interface elements and uses older Graphics Device Interface
(GDI) to render graphics. Figure 1-1 illustrates the differences between the visual interface
rendering approaches for WPF and Windows Forms applications.

More Info Visit MSDN at http://msdn.microsoft.com/en-us/library/ms750441.aspx to get


more details on the WPF architecture.

XAML—A Declarative Language for .NET Applications


As mentioned earlier, XAML is at the center of the declarative user interface (UI) WPF framework
because it implements the abstracted user interface layer. XAML is becoming a core UI definition
language for .NET Framework–based applications. Using XAML, you can define and develop user
interfaces for WPF and Silverlight applications and custom workflow activities for WF version 4.0.

4  Part 1 XAML Basics


You define and implement these user interfaces using a set of XAML controls provided as part of
the WPF framework. These XAML controls are derived from a set of WPF presentation framework
classes that can be hosted in either a window (WPF applications) or a page (Silverlight applications) to
render the defined user interface at runtime using a XAML parser.

WPF

Windows Forms Presentation Framework−XAML

Presentation Core

Common Language Runtime (CLR)

Rendering All Visual


Interface Components

Media Integration Library (MIL)


Rendering Rendering
Standard UI Graphics
Elements

Direct 3D

Operating System

User32

GDI

Device Drivers

Figure 1-1 Rendering WPF and Windows Forms applications.

Caution Not all XAML controls are interoperable between WPF, Silverlight, and WF
­ pplications. In addition, the XAML parsers for each platform are also different. You will
a
need to use and set appropriate WPF, Silverlight, and WF platform specific–XAML controls
and compile applications using the corresponding platform.

Chapter 1 Introducing XAML 5


XAML Is Part of the Microsoft Open Specification Program (OSP)
You are probably aware that XAML is currently a Microsoft domain-specific language. To p­ rovide
­transparency and simplify the development of XAML applications by the broader developer ­community,
Microsoft published the technical specification of XAML Object Mapping for WPF and ­Silverlight in March
2008, under its Open Specification Promise (OSP) program. Microsoft is ­committed to maintaining those
specifications.

The XAML technical specification documentation provides details on XAML’s data model for types,
object hierarchies, and the techniques for mapping between XML and the object hierarchy data model.
It also documents the WPF and Silverlight vocabulary of types that can be used with XAML specifications.
Developers can use the WPF and Silverlight XAML technical specification documentation in conjunction
with publicly available standard specifications, computer language design, and implementation art to fully
understand and take advantage of XAML.

More Info Visit MSDN at http://msdn.microsoft.com/en-us/library/dd361847.aspx to


­download the various releases of XAML Object Mapping, and the WPF and Silverlight
­technical specification documentation.

XAML Structure
Figure 1-2 provides a quick overview of defining a button. In the example, the button width is set to
100, the button background color is set to LightGray, and the content (the button label) is set to “I am
a Button“ in XAML. The example also shows an identical Button object created in C#, with its related
properties set in code.

I am a Button

XAML C#

<Button Width="100">I am a Button Button b1 = new Button( );


<Button.Background> b1.Width = 100;
LightGray b1.Content = "I am a Button";
</Button.Background> b1.Background = new
</Button> SolidColorBrush(Colors.LightGray);

Figure 1-2 Defining a Button object and its properties in XAML and in C# code-behind.

A XAML file has a .xaml file extension. As shown in Figure 1-2, any XAML file consists of XML-like
structured information that defines the relationships among various XAML controls. At runtime,
these controls render as an object tree to create the user interface. In other words, XAML itself is
an ­abstraction—it simply describes objects. This abstraction lets XAML serve as the UI description

6  Part 1 XAML Basics


language for several different .NET application types (WPF, Silverlight, and WF). The properties
you define within the XAML elements (such as the Width, Content, and Background properties of
the Button control in Figure 1-2) control the look and feel of the particular user interface object
represented by that XAML element. You can also determine how or whether a control binds with
data. When you bind a control, it can display information (often from a database) unavailable at
design time, and obtained only at runtime.

More Info See Chapter 2, “Object Elements and Attributes,” for more details on XAML
syntax, XAML object elements, and attributes.

Dynamic User Interface


As shown in Figure 1-3, the key difference and advantage of using XAML—compared to building the user
interface by creating and adding the controls in code-behind—is that XAML provides a declarative and
separately compiled and rendered way of describing the user interface. User interface controls defined
in code are described at design time and executed at runtime. In contrast, controls defined in XAML are
stored separately from compiled code in .xaml files. At runtime, the XAML file is loaded and parsed by a
XAML parser, and the user interface is then rendered dynamically. Thus if you change the user interface
within a XAML file and redeploy it, the updated XAML content will be parsed and rendered; any changes
in the user interface definition will be reflected in the user interface.

XAML’s capability to develop an externalized and loosely coupled user interface enables developers
to develop and modify the user interface without affecting the underlying program code and without
recompiling the project for each UI change, which can significantly reduce the overall effort required for
application development and testing.

C#
Compile (Design-time)
Button b1 = new Button( ); and Execute (Runtime)
b1.Width = 100; I am a Button
b1.Content = "I am a Button";
b1.Background = new
SolidColorBrush(Colors.LightGray);

XAML Load, Parse,


Render and Display
<Button Width="100">I am a Button At Runtime
<Button.Background> I am a Button
LightGray
</Button.Background>
</Button>

Figure 1-3 Defining a Button object with its properties in XAML and using C# in code-behind.

Chapter 1 Introducing XAML 7


When working with XAML, remember that the WPF XAML parser is full-featured, whereas the
Silverlight XAML parser ships with a more limited feature set. As mentioned earlier, not all XAML
controls are interoperable between WPF, Silverlight, and WF applications. You will need to use the
appropriate WPF, Silverlight, and WF platform–specific XAML controls and compile applications using
the specific platform to which you want to deliver.

More Info Visit MSDN at http://msdn.microsoft.com/en-us/library/cc917841.aspx for more


details on the differences between WPF and the Silverlight XAML parser.

Decouple Control Style Definitions


Applications should maintain consistency throughout to give users a predictable experience, including
using the same color set, fonts, font sizes, and styles. Typically, ensuring this consistency can become quite
challenging when you are using multiple controls of similar types in single or multiple XAML files within
the same application, or across multiple applications. However, the WPF and Silverlight platforms help, be-
cause it ­provides the capability to easily externalize and decouple style sheets, which XAML elements can
then r­ eference from within XAML files to help maintain a consistent user experience. The approach and
­capability is similar to the Cascading Style Sheets (CSS) approach used in standard HTML web applications.

Figure 1-4 demonstrates how you can define a style within a XAML file as a resource or as an
­external resource file, and apply that style to a Button control.

Defining a Style
Button
<Style x:Key="ButtonStyle5" TargetType="Button">
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Background" Value="Green"/>
<Setter Property="FontStyle" Value="Italic"/>
<Setter Property="FontFamily" Value="Verdana"/>
<Setter Property="FontSize" Value="16"/>
</Style>

Applying a Style

<Button Style="{StaticResource ButtonStyle5}"


Width="115" Content="Button"/>

Figure 1-4 Defining and applying styles to XAML controls.

More Info See Chapter 5, "Resources, Styles, and Triggers," for more details on styles and
resources for XAML.

8  Part 1 XAML Basics


Customized Design of XAML Controls
One of the biggest advantages of WPF’s separation of the visual appearance of controls defined in XAML
from business logic implemented mainly in code is that a designer not only controls the common styles
of controls but can also alter the default look and feel of the control. For example, you might change
the ­default look and feel of a button to make it look like a star! In WPF you can use a ControlTemplate to
­define the visual structure and behavior of a control without affecting its functionality.

Each control can exist in a number of possible states, such as disabled, having the input focus, a state
where the mouse is hovering over it, and so on. A control template lets you define what a control looks
like in each of these states. Sometimes this is referred to as changing the look and feel of the control,
­because changing the visual appearance of each state alters how a user sees and experiences a control.

Figure 1-5 demonstrates how you can define a control template to change the appearance of a
Button control to make it look like an ellipse.

Button Defining a ControlTemplate

<ControlTemplate x:Key="ButtonControlTemplate1" TargetType="Button">


<Grid>
<Ellipse Margin="8,0,0,0" Stroke="#FF000000">
<Ellipse.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,1">
<GradientStop Color="#FF4292F2"/>
<GradientStop Color="#FFC9EDF7" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<TextBlock Margin="48,19,19,14" Text="Button" TextWrapping="Wrap"/>
</Grid>
</ControlTemplate>

Applying a ControlTemplate

<Button Margin="50" Height="56" Width="119" Content="Button"


Template="{StaticResource ButtonControlTemplate1}"/>

Figure 1-5 Defining and applying a control template to XAML controls.

Integration with Code-Behind to Control Behavior


In general, markup languages such as HTML are mainly limited to defining the look and feel of the
user interface; most markup languages cannot define the behavior of the user interface by controlling
user interactions and defining various application actions. The typical way to implement some level of
business logic within an HTML file is to use a scripting language such as JavaScript or VBScript.

Chapter 1 Introducing XAML 9


In contrast to HTML, XAML was specifically developed for use with .NET Framework components. It
can use the .NET Framework platform and the Microsoft design and development tools and extend its
capabilities because it’s not limited simply to defining the user interface. It also enables interaction by
integrating XAML controls with managed code such as C# and VB .NET, and even dynamic languages
such as Ruby and Python.

More Info See the article “Creating Interactive Bing Maps with Silverlight and IronRuby,” at
http://msdn.microsoft.com/en-us/magazine/ee291739.aspx for an example of how IronRuby
dynamic language integrates events of XAML objects to implement required business logic.

Each XAML file for WPF, Silverlight, or WF project has a corresponding code-behind file, which
Microsoft development tools such as Visual Studio or Expression Blend create for you automatically.
However, a third file type is associated with the XAML file. Figure 1-6 illustrates the full class imple-
mentation for the MainWindow XAML file of a standard WPF project created using either Visual
Studio or Expression Blend.

MainWindow Class
As part of build process
(or in Visual Studio
upon saving the XAML MainWindow.xaml.cs
file), a code-behind file
WPF XAML File is generated based on
XAML
MainWindow.xaml

MainWindow.g.i.cs

Code-behind files
create the WPF
MainWindow class

Figure 1-6 Full class implementation of XAML.

Note As defined on MSDN, “code-behind is a term used to describe the code that is joined
with markup-defined objects, when a XAML page is markup-compiled.” See http://msdn.
microsoft.com/en-us/library/aa970568.aspx to get more information on the code-behind
capabilities of XAML.

If you create a WPF application project by selecting WPF Application template in Visual Studio, you
will get a default MainWindow.xaml file. If you expand the MainWindow.xaml file in the Visual Studio
Solution Explorer, you will see an associated code-behind file named either MainWindow.xaml.cs file
(when you create a C# WPF project) or MainWindow.xaml.vb (when you create a Visual Basic WPF
project). This code-behind class is usually used to manage events and as a gateway to integrate with
other application components and services to implement the business logic.

10  Part 1 XAML Basics


Now, open this code-behind file in the code editor. Locate the class constructor and right-click the
InitializeComponent() method. Select the Go To Definition option from the shortcut menu. You will
see that the InitializeComponent definition code opens a MainWindow.g.i.cs file. MainWindow.g.i.cs is
a generated file based on the XAML defined in the MainWindow.xaml file. Any objects in the XAML
file that have an x:Name cause the creation of a class member in the generated file.

The following code snippet demonstrates the default MainWindow.xaml.cs file of the WPF application
and the InitializeComponent() method (in bold font) within the class constructor:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

XAML defines the language features x:Class, x:Subclass, and x:ClassModifier directives, which (as you
will explore more deeply in Chapter 2) enable integration of the XAML markup file with the code-behind
­partial class. You must derive the partial class defined in the root element of the XAML markup file ­using
the x:Class attribute. This class usually gets defined automatically by Visual Studio, using the naming
convention <XAMLFileName.xaml>.cs or <XAMLFileName.xaml>.vb, depending on which .NET l­anguage
you’re using. The following code snippet shows the definition of the x:Class attribute (in bold font) d
­ efined
in the Window root element of the MainWindow.xaml file of the WPF application.

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>

Chapter 1 Introducing XAML 11


Note Because XAML is a declarative language, it can contain data binding, state management,
triggers, and so on as part of the UI definition. That means that design patterns such as the
Model-View-Controller (MVC) and Model-View-Presenter (MVP) that were developed for
service-oriented applications are not the best-fitting patterns for WPF-based applications.
Instead, a new design pattern called the Model-View-View-Model (MVVM) pattern has
been developed to define the user interface layer for XAML-based applications. Although
MVVM was largely derived from the concept of MVC and MVP patterns, it differs by defining a
view model that represents both a data model and behavior for views, and allows views to
bind to the view model declaratively within XAML. Visit http://msdn.microsoft.com/en-us/
magazine/dd419663.aspx to get an overview of how you can develop WPF applications using
the MVVM design pattern. Also see http://weblogs.asp.net/dwahlin/archive/2009/12/08/
getting-started-with-the-mvvm-pattern-in-silverlight-applications.aspx to get an overview
on how to develop Silverlight applications using MVVM.

Inline Code
The WPF XAML namespace also supports an additional x:Code directive element that can contain
inline programming code (in C# or Visual Basic) to implement business logic directly within the XAML
file. Programming code within the x:Code element must be entered inside a <[CDATA[…]]> segment
so that it will be processed as code rather than as XML by the XAML parser.

The following example implements the Click event of a Button control within the XAML file as
inline code (in bold font). The code is written in C#, and is defined right next to the definition of the
Button control, but within an x:Code element:

<Button Name="button1" Click="button1_click">Click Me!</Button>


<x:Code>
<![CDATA[
void button1_click(object sender, RoutedEventArgs e)
{
button1.Content = "Inline Code Works!!";
}
]]>
</x:Code>

Warning Despite the existence of the <x:code> element, inline coding within XAML is not
­considered a best practice, and its use is not recommended except in special circumstances. It’s
­defnitely not the best way to implement complex business logic. Inline code has some limitations
that make implementing reusable code across a project considerably more c­ hallenging. In
­addition, it’s more difficult to code, maintain, and support complex business logic in inline code.

The inline code must be defined within the XAML file. The scope of inline code is limited to the scope
of the partial class created for that particular XAML instance.

12  Part 1 XAML Basics


You cannot use using (C#) or Imports (VB.NET) statements. Instead, you must fully qualify
­references to code entities outside the partial class.

The <x:Code> element must be an immediate child element of the root element of the XAML
­production. Moreover, although XAML itself has the advantage of abstracting the user interface
­definition of the application from the implementation of the business logic, inline code does not pro-
vide that abstraction, because it’s defined directly within the XAML file.

Caution The x:Code directive (and thus inline coding) is supported only by the WPF
XAML parser—it is not supported by the Silverlight XAML parser. Therefore, you cannot
­implement inline coding in Silverlight applications. The Silverlight XAML parser also does
not guarantee preservation of CDATA segment content.

Silverlight
Silverlight is an extension of the .NET Framework–based technology platform to develop
­cross-browser, cross-platform, and cross-device Rich Internet Applications (RIAs). RIAs are web
­applications that have features and functionality similar to traditional desktop applications, including
rich and interactive user interfaces.

You can deploy Silverlight applications as plug-ins (in both in-browser and out-of-browser modes) that
run in a sandboxed environment. Silverlight is built upon lightweight components of the .NET ­Framework
that are a subset of the full WPF libraries. Silverlight applications do not require users to perform a
full i­nstall of the .NET Framework; instead, users need to install only a small Silverlight plug-in on their
­Windows or Mac (Intel processer–based) computers, or Windows Phone 7 mobile devices.

Note To install the latest version of Silverlight and get the latest information on Silverlight,
visit Microsoft’s official Silverlight website at http://www.silverlight.net/getstarted/.

Like WPF Windows applications, the declarative XAML markup language used by Silverlight is at the
center of the declarative user interface (UI) framework. You can use the same Microsoft development tools
(Visual Studio and Expression Blend) to define Silverlight user interfaces in XAML and you can implement
business logic using standard .NET languages. However, there is a significant difference between the set of
XAML controls available for WPF and those available for Silverlight. In addition, the Silverlight platform has
limited .NET Framework libraries and its XAML parser as compared to the full WPF platform.

The initial versions of Silverlight (Silverlight 1.0 and 2.0 versions) were mainly targeted toward
building media applications, so it focused on media integration, vector graphics, and animation. Later
versions (Silverlight 3 and Silverlight 4) enhanced and streamlined Silverlight’s media applications
capabilities, and extended the product focus to implementing data-driven enterprise line of business
(LoB) applications. Silverlight 5 version extended the LoB applications capabilities and added support
for mobile applications development, as well as support for gaming and 3-D animations.

Chapter 1 Introducing XAML 13


With Silverlight 5, Silverlight has reached maturity as an enterprise platform for developing and
deploying media and data-driven RIAs. It supports the required security, maintainability, flexibility,
scalability, and as a result, it is being adopted across a wide range of industries.

Note HTML5 has extended the HTML platform capabilities to support native markup
­integration with multimedia (audio and video elements), enhanced user interface controls
(such as calendar, date, time, email, URL, and search elements), and content integration
(such as article, footer, header, and section elements). The new capabilities in HTML5 will
reduce the need for custom scripting and custom plugins (such as Adobe Flash) when
­developing rich interactive applications. However, the implementation of the HTML5
­specification is not standard. As a result, different browsers may take different approaches
and render HTML5 differently. This is a challenge for developers trying to develop HTML5-
based applications that provide consistent results across many different potential browser
targets. Offsetting this problem is the advantage that HTML is a cross-platform technology
platform supported by all modern operating systems (including operating systems such as
Windows, Linux, OS X, iOS, and Android).

The Microsoft .NET Framework


When it released XAML, Microsoft also provided a set of development and designer tools to use the
capabilities of XAML and the .NET Framework during the design and development process, as shown
in Figure 1-7.

Artists- Developers-
Define Visuals Implement Logic
Button

Button

XAML

XAML WCF

Expression Blend Media WF Visual Studio

Data VB.NET,
Sources C#, ...

Data
Sources

Figure 1-7 Separation of the design and development processes.

14  Part 1 XAML Basics


The WPF platform enables separation of the visual appearance of the application from the actual
implementation of the business logic. In addition to Visual Studio as a development tool, Microsoft
introduced Expression Blend (part of Expression Studio). Expression Blend is a tool that designers can
use to create custom user interfaces in XAML. Using Expression Blend you can build sophisticated,
rich, and interactive user interfaces as well as create 2-D and 3-D vector graphics and animations—all
without needing a deep knowledge of XAML syntax, and also without needing any .NET language
programming knowledge. This separation finally frees developers from building UI elements. Design-
ers can work on the design while the development team starts implementing the code-behind and
other application components and services. In other words, developers and designers can work in
concert to implement both the UI and the actual business logic. And because Expression Blend can
load and use Visual Studio projects and files directly, artists and developers can work on the same
WPF, Silverlight, or WF projects, switching easily from Expression Blend to Visual Studio project and
vice versa.

Before ending this chapter, it’s worthwhile to provide a quick high-level overview of the key design-
time and runtime components of the .NET Framework so you’ll understand how they fit together.

Design-Time Components
Since .NET Framework 3.0, Microsoft has introduced the following key foundation components that
support a unified programming and deployment model:

■■ Windows Presentation Foundation (WPF), which uses XAML to define and develop abstracted,
dynamic, rich, and interactive user interface layer providing integration capabilities with data,
media, graphics, animation, and documents

■■ Windows Communication Foundation (WCF), a service-oriented messaging system that can


integrate across platforms and that supports industry-standard networking protocols

More Info See this MSDN page (http://msdn.microsoft.com/en-us/library/ms735119.aspx)


to get more information on WCF. For an introduction to the new WCF f­ eatures in .NET
Framework 4.0, see http://msdn.microsoft.com/en-us/library/dd456779.aspx.

■■ Windows Workflow Foundation (WF), which provides a framework for developing workflow-
driven task integration and automation

More Info Visit the MSDN page at http://msdn.microsoft.com/en-us/library/dd489441.aspx


for more details on WF.

Chapter 1 Introducing XAML 15


Runtime Cross-Platform Components
■■ The Common Language Runtime (CLR), the Dynamic Language Runtime (DLR) and Base Class
Library (BCL) for .NET Framework components are key components of the runtime cross-platform
execution engine.

Figure 1-8 demonstrates the language-independent execution model of .NET applications


developed using both static languages such as Visual Basic .NET, C#, and J#, as well as
dynamic languages such as IronRuby and IronPython.

Languages Dyanamic Languages

VB.NET C# J# IronRuby IronPython

SOURCE CODE
Compile Time

Language Dynamic Languages Runtime


Complier
VB.NET C# J# Expression Dyanamic Objects
Complier Complier Complier Trees Interoperability

.NET Base
Ruby
Class Library
Common Intermediate Language (CIL) / Libraries
(BCL)
Microsoft Intermediate Language (MSIL) Python
Custom Libraries
Assemblies BYTE CODE
Runtime

Common Language Runtime (CLR)

NATIVE CODE

Figure 1-8 Execution model of .NET Framework 4.0–based applications and services.

■■ The Common Language Runtime (CLR) is the underlying runtime execution engine of the
.NET Framework that provides a managed and secured application and services execution
­environment. The CLR enables abstracted development of application components and
­services using different languages, which get compiled to the common intermediate language
(CIL) bytecode format at design time. At runtime, CLR will translate CIL bytecode to the native
code using the Just-In-Time (JIT) compiler.

More Info Visit the MSDN page at http://msdn.microsoft.com/en-us/


library/8bs2ecf4.aspx for more details on the CLR.

■■ Dynamic Language Runtime (DLR) is a .NET Framework hosting model for dynamic languages,
which provides a set of .NET Framework libraries and services for .NET and Silverlight that
­create a bridge between dynamic languages and the CLR in .NET and Silverlight.

16  Part 1 XAML Basics


More Info Visit the MSDN page at http://msdn.microsoft.com/en-us/library/
dd233052.aspx for more details on DLR.

■■ Base Class Library (BCL) is a foundation for development of any .NET Framework–based
­applications or services. It is a library of classes, interfaces, and value types that provides the
basic and system-level functionalities such as processing and managing XML files, integration
with database, integration with file systems and connected devices, animation, graphics and
media management, error and diagnostic management, integration with industry standard
protocols, providing encryption mechanisms, LINQ, parallel computing, and capabilities to
integrate with COM Interops.

More Info Visit the MSDN page at http://msdn.microsoft.com/en-us/library/


gg145045.aspx for more details on BCL.

Summary
The declarative XML-based eXtensible Application Markup Language (XAML) is at the center of the
WPF framework. You use XAML to define and develop abstracted, dynamic, rich, and interactive user
interface layers that can integrate with data, media, graphics, animation, and documents.

Using WPF, you can develop rich and interactive Windows desktop applications that can provide
sophisticated and realistic user experiences. Silverlight is a subset of WPF; you can use it to develop
browser-hosted cross-platform, rich Internet applications as well as applications for Windows 7.x
series mobile devices.

This chapter clearly shows that Microsoft has established a robust software and services development
and delivery platform—the Microsoft .NET Framework—built upon solid core software development
concepts such as object-oriented programming and language and environment independence. Together,
these support the following essential attributes of software platform and services:

■■ Device- and platform-independent application services With the introduction of


­Silverlight and the Dynamic Language Runtime (DLR), the .NET Framework offers broad
­support for development of cross-platform applications and services suitable for a broad
range of development, deployment, and usage scenarios.

■■ Dynamic and flexible services-focused architecture With the introduction of WPF, WCF,
and WF and support for managed code integration, you can now develop service-oriented
flexible software services using the .NET Framework deployable to both enterprise and cloud
platforms.

Chapter 1 Introducing XAML 17


■■ Aesthetic and high-performance user interfaces XAML gives you the ability to define
abstracted user interfaces that can support five usability dimensions:

o Availability (can I get to it?)

o Responsiveness (Is it fast enough?)

o Clarity (can I figure it out?)

o Utility (does it have what I want?)

o Safety (is my identity and information secure?)

The next chapter, “Object Elements and Attributes,” will provide a detailed walkthrough of XAML
basics—all the key information you need to know to create visuals for the user interface layer of
XAML-driven applications.

18  Part 1 XAML Basics


Want to read more?
Microsoft Press books are now available through O’Reilly Media.
You can buy this book in print and or ebook format, along with
the complete Microsoft Press product line.

Buy 2 books, get the 3rd FREE!


Use discount code: OPC10
All orders over $29.95 qualify for free shipping within the US.

It’s also available at your


favorite book retailer,
including the iBookstore,
the Android Marketplace,
and Amazon.com

Spreading the knowledge of innovators oreilly.com

You might also like