Silverlight 2 in Action Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Silverlight 2 in Action CHAD A. CAMPBELL JOHN STOCKTON MANNING Greenwich (74° w. long.) Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

For online information and ordering of this and other Manning books, please visit www.manni ©2009 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted

Many of the designations used by manufacturers and sellers to distinguish their products ar

Recognizing the importance of preserving what has been written, it is Manning’s policy to h Manning Publications Co. Sound View Court 3B Greenwich, CT 06830 Development editor: Copyeditor: Typesetter: Cover designer: Cynthia Kane Andrea Kaucher Dottie Marsico Leslie Haimes ISBN 1-933988-42-8 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 14 Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

brief contents 1 2 3 4 5 6 7 8 9 10 11 12 ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ Introducing Silverlight 1 Harmony with the web 22 56 88 126 159 Back to the basics: Layout Bringing it to life: Animation v Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

contents foreword xiii preface xv acknowledgments xvii about this book xx 1 Introducing Silverlight 1.1 1.2 1.3 Productivity 2 ■ 1 2 3 ■ Silverlight up your life Performance 7 Portability 3 8 Why can’t we be friends? 6 The developer experience ■ The designer experience Compound 12 XAML 8 ■ ■ ■ Code behind 9 Namespaces 10 properties 12 Attached properties 1.4 1.5 Blending it together Summary 21 13 2 Harmony with the web 2.1 22

The relationship between Silverlight and the HTML DOM 23 The HTML Document Object Model 24 The Silverlight plug-in 25 The Silverlight Object Model 2 ■ ■ vii Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

4 The Silverlight Application Model The manifest file application 41 ■ ■ 39 44 40 The Silverlight Application dependencies 2.js instance of the Silverlight plug-in 28 Creating an 2.3 Integrating a Silverlight plug-in ■ 29 Relating the Silverlight application to the HTML DOM 30 Clarifying the initial experience 3 ■ 2.1 A Canvas for your imagination Arranging content of a Canvas packing a punch 60 58 56 57 ■ .6 Summary 55 3 Back to the basics: Layout and text 3.viii CONTENTS 2.5 Interacting with the HTML DOM 44 Managing the web page from managed code 44 Working with the user’s browser window 48 Bridgi 2.2 Creating a Silverlight plug-in 26 27 ■ The Silverlight utility file: Silverlight.

Henrik Thiesen <henrik.2 3.6 The UIElement and FrameworkElement Properties 80 ■ 80 Methods 85 Summary 86 4 Handling user interaction 4.thiesen@seb.3 The StackPanel: Stack ’em deep 61 The power Grid 62 Arranging Grid content 63 Sizing it up 65 Working with the Grid programmatically 68 Customi ■ 3.dk> .5 3.4 Displaying text ■ 72 ■ Font properties 72 Flow control properties 76 Spacing 78 76 ■ Text 3.The Canvas: 3.1 Capturing the keyboard 88 89 92 89 ■ Understanding device support Trapping the mouse Licensed to SEB Link A/S .

8 4.2 4.5 4.9 Date controls Calendar 110 110 ■ DatePicker 115 113 Choosing from a numeric range Using the ProgressBar Popping up a dialog box ■ 114 115 118 Implementing a Slider Displaying visual prompts 116 116 ■ Prompting for a file 121 Miscellaneous controls Creating a border 121 ■ .6 4.7 4.3 Delivering text controls Handling basic text 96 ■ 96 Collecting sensitive data 98 Button controls 99 ■ ■ The Button 100 The HyperlinkButton 101 The RadioButton 102 The CheckBox 104 4.CONTENTS ix 4.4 The ItemsControl 105 The ListBox 105 The ComboBox The TabControl 108 ■ 107 4.

121 Collecting drawings Summary 124 5 Getting down with data binding 5.5 Language Integrated Query (LINQ) ■ ■ 149 Introducing LINQ 149 LINQ to Objects 153 LINQ to XML 154 LINQ-ing it together 156 .4 The DataGrid 141 Displaying your data Sorting items 148 142 ■ Editing grid data 147 5.3 Customizing the display 136 136 ■ Converting values during binding data templates 139 Creating 5.2 Understanding your data source ■ ■ 131 Binding to a property 131 Binding to an object 133 Binding to a collection 134 5.1 Binding with your data 127 Mastering the binding syntax binding mode 129 126 127 ■ Choosing a 5.

Henrik Thiesen <henrik.thiesen@seb.6 Summary 158 Licensed to SEB Link A/S .5.dk> .

3 Connecting to data sources Using SOAP services ■ 165 Time for a REST 177 ■ 165 ■ 170 Reading Making the data usable 173 Reading POX 173 Converting JSON syndicated feeds 179 6.1 ■ 159 160 Trust.4 Using advanced services ■ 185 ■ WCF service enhancements 185 WCF duplex services 186 Connecting to sockets 191 6.1 194 ■ . and browser limitations ■ It’s all a matter of trust 160 Making your application secure 163 Limitations of the browse 6.5 Summary 193 7 Managing digital media 7.x CONTENTS 6 Networking and communications 6. security.2 6.

Henrik Thiesen <henrik.dk> .3 Interactive playback 209 Controlling the play state 209 Timely interaction 210 Going full screen 212 ■ ■ 7.1 Getting in shape 227 226 ■ ■ A Line in the sand 228 Rectangle 229 The ellipse 230 Polyline 230 Polygon 231 ■ ■ Licensed to SEB Link A/S .thiesen@seb.2 Playlists: for that web-based mixtape 205 Understanding client-side playlists playlists 207 205 ■ Using server-side 7.6 Using images in your application Basic imaging 216 ■ 215 216 ■ Deep Zoom The 7th inning stretch: Dealing with dead space 222 I’ll have none of this stretching business 222 Uniform sizing 223 Fill the area 224 Uniform ■ ■ 7.5 7.Stunning audio and video 195 Getting to the source 195 Common properties 199 Audio specifics 201 Video specifics 203 The ■ ■ 7.4 Using protected content 213 Requesting protected content 214 Retrieving the PlayReady components 214 Unlocking protecte ■ ■ 7.7 Summary 225 8 Getting a grip on graphics 8.

.

2 Geometry 231 ■ Simple geometries 232 Path geometries Composite geometries 235 233 8.4 Transforms 242 ■ ■ RotateTransform 242 ScaleTransform 243 SkewTransform 243 TranslateTransform 244 TransformGr 8.2 253 Animation: It’s about time 254 Mastering the timeline 256 What type of property are you animating? 256 Where are you starting from and where are you ■ 9.CONTENTS xi 8.3 Storyboarding 264 Understanding the storyboard 264 Hitting the target 265 Controlling the Storyboard 267 Bein ■ ■ ■ 9.3 Brushes 235 ■ ■ SolidColorBrush 236 LinearGradientBrush 237 RadialGradientBrush 239 ImageBrush 240 VideoBru 8.4 Key framing 271 Interpolation: It’s about acceleration is everything 276 273 .1 9.5 8.6 Blending it together Summary 251 245 9 Bringing it to life: Animation 9.

1 278 ■ Being resourceful 279 Declarative resources 279 Accessing loose resources 282 Bundling resources 284 ■ 10.Henrik Thiesen <henrik.3 Giving your elements style Defining the look 287 ■ 286 289 Targeting style definitions 291 ■ Creating templates 290 Creating reusable Building a control template templates 295 10.thiesen@seb.■ Timing 9.2 10.4 Dealing with visual states 295 296 Understanding the components Licensed to SEB Link A/S .5 Summary 277 10 Giving it style 10.dk> .

6 10.xii CONTENTS 10.2 11.1 Creating a user control 339 Defining the appearance 339 Defining the behavior 340 Calling the control 344 ■ ■ 338 12.5 10.3 11.2 .7 Leveraging the VisualStateManager 298 Sharing your effects 301 Summary 303 11 Enhancing the experience 11.6 The Dynamic Language Runtime (DLR) Dynamic typing 332 ■ 332 335 Metaprogramming Summary 337 12 Share the light: Distribution and deployment 12.5 11.4 Using XAML at runtime 314 BackgroundWorker 316 Doing the work 316 ■ Updating the UI 317 Retrieving content on demand 321 Requesting content 322 Managing larger download requests 323 Loading the content 325 ■ ■ 11.1 305 ■ Storing data in isolated storage 306 IsolatedStorageFile: The virtual filesystem 306 Reading and writing files: The isolated sto ■ 11.

3 Using a custom splash screen ■ ■ 348 Creating the appearance 348 Integrating the custom splash screen 350 Monitoring the load pr 12.4 Hosting with Silverlight Streaming 351 Preparing to stream! 352 it! 354 Use it! 354 ■ ■ Pack it up! 352 ■ Ship 12.k. 12.Architecting navigation in Silverlight ■ ■ 344 Setting up the architecture 345 Implementing a navigator 346 Navigating between pages (a.Henrik Thiesen <henrik.5 Summary index 357 355 Licensed to SEB Link A/S .thiesen@seb.dk> .

dk> .foreword The technologies powering the web are a heterogeneous mix of features and initiatives.Henrik Thiesen <henrik. some xiii Licensed to SEB Link A/S .thiesen@seb.

Henrik Thiesen <henrik.dk> . you will find many things in this book you did not previou Licensed to SEB Link A/S .xiv FOREWORD Silverlight applications before.thiesen@seb.

preface I have been waiting for Silverlight for quite some time.Henrik Thiesen <henrik.thiesen@seb. I began writing professionalgrade xv Licensed to SEB Link A/S .dk> .

thiesen@seb.dk> . WPF/E was renamed Silverlight.Henrik Thiesen <henrik. Eventually. it con Licensed to SEB Link A/S .xvi PREFACE heavily focus on WPF until WPF/E matured.

com website that compa xvii Licensed to SEB Link A/S .thiesen@seb.dk> .bubblemark.acknowledgments There were literally dozens of individuals who worked to make this book as valuable as poss ■ ■ ■ ■ ■ Alexey Gavrilov—Alexey created the invaluable http:/ /www.Henrik Thiesen <henrik.

Henrik Thiesen <henrik.dk> . there are those that hav Licensed to SEB Link A/S .xviii ACKNOWLEDGMENTS ■ ■ chapter 11. a larg Personal thanks In addition to the individuals who helped us with the book itself. M This book wouldn’t be what it is without the help of these individuals. In addition. Thank you.thiesen@seb. for helping us make this content as accurate as possible. Michael.

ACKNOWLEDGMENTS xix John would like to thank his loving wife Kristi for the patience and support while he worke Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik.thiesen@seb.

we’ve created a companion website.thiesen@seb.Henrik Thiesen <henrik.about this book The overall goal of this book is to inform and educate you on the exciting and powerful Sil ■ ■ ■ Figure—Visual depictions that summarize data and help with the connection of complex concep In addition to these valuable learning devices.dk> . the best xx Licensed to SEB Link A/S .

thiesen@seb. this list may be somewhat overwhelming.dk> . If you’d like a guide Licensed to SEB Link A/S . Silverlight 2 Beta 1. But. Silverlight 2 Beta 2.1 Alpha.ABOUT THIS BOOK xxi of Microsoft’s powerful creative tools: Microsoft Visual Studio 2008 and Microsoft Expressi Audience This book is intended for developers with a desire to create rich. it also provides a grea ■ ■ ■ ■ Silverlight 2 (required) Microsoft Visual Studio 2008 SP1 (recommended) Microsoft Expressio We’ve made conscientious attempts to ensure that the information and screenshots are consis ■ ■ ■ ■ Silverlight 1. and finalized on Silverl If you’re new to these tools.Henrik Thiesen <henrik. valuable. web-based user The gear: what you need This book provides a lot of opportunity for hands-on learning.

Henrik Thiesen <henrik.dk> .thiesen@seb. This tour will focus on Sil Licensed to SEB Link A/S .xxii ABOUT THIS BOOK Roadmap This book is designed to give you a guided tour of Silverlight.

silverlightinaction.blogspot.com Chad’s blog—http://cornucopia30. We post nearly all comments. This includes user Code conventions All the code used in this book will be presented in a monospace font. if you in About the authors Chad Campbell is a Microsoft MVP and solutions architect.Henrik Thiesen <henrik.ABOUT THIS BOOK xxiii Chapter 12 discusses sharing your Silverlight creations with the world.dk> . but.co All comments sent to these blogs are moderated.thiesen@seb. This code can be in o Author Online The purchase of Silverlight 2 in Action includes free access to a private forum run by Mann ■ ■ ■ Book website—http://www. He has been developing enterprise Licensed to SEB Link A/S .

” J Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik.xxiv ABOUT THIS BOOK In addition. and how-to examples. the In Action books are designe About the cover illustration The figure on the cover of Silverlight 2 in Action is a “Janissary in Dress of Ceremony. Chad has a BS degree from Purdue University where he focused his studies on co About the title By combining introductions.thiesen@seb. overviews.

ABOUT THIS BOOK xxv turned down.Henrik Thiesen <henrik. With the seller flying back to Ankara that evening the situation was getting h Licensed to SEB Link A/S .dk> .thiesen@seb.

Licensed to SEB Link A/S .dk> .thiesen@seb.Henrik Thiesen <henrik.

thiesen@seb.Henrik Thiesen <henrik.dk> . and y Silverlight content has been shown to run on Windows Mobile 6 and Nokia devices running the 1 Licensed to SEB Link A/S .Introducing Silverlight This chapter covers ■ ■ Learning about the advantages of Silverlight Creating an understanding of the developer/ de ■ You’ve purchased this book wanting to learn about Microsoft’s Silverlight 2 platform.

2 CHAPTER 1 Introducing Silverlight active application space. we’ll examine the designer/developer collaboration advancem 1. and another sol Licensed to SEB Link A/S .1 Productivity Imagine how painful grocery shopping would be if only one store sold bread.dk> .1. Then.1 Silverlight up your life The winds of excitement are whipping around the World Wide Web as individuals increasingly 1.Henrik Thiesen <henrik.thiesen@seb.

2 Performance Getting stuck in the quicksand of long response times can be a frustrating experience. cross-platform user experience juggernaut designed with por Licensed to SEB Link A/S .3 Portability Silverlight is a cross-browser.Silverlight up your life 3 quickly.dk> . With a powerful developmen 1.thiesen@seb.1.Henrik Thiesen <henrik. enabling you to focus on solutions instead of problems.1. Long 1.

The Other portion represents the plat 2 3 The Internet Explorer and Firefox statistics were compiled using a freshly formatted Dell I Licensed to SEB Link A/S . per platform.1 Calculated frames per second.4 CHAPTER 1 Introducing Silverlight Figure 1.2 Silverlight supports the platforms listed.dk> . per technology.Henrik Thiesen <henrik. natively Figure 1. and per browser2 Those interested in Silverlight often ask: What does everywhere really mean? Well.thiesen@seb.

“Browser Market Share.Silverlight up your life 5 The specific operating systems listed in this figure account for approximately 97% of the o NOTE Figure 1.dk> .Henrik Thiesen <henrik. Operating Systems a Licensed to SEB Link A/S .” Marketing Share for Browsers. it must run within the security sandbox of an int Figure 1.thiesen@seb.3 Silverlight content can run within the browsers and versions listed within the c 4 Net Applications. Silverlight 2 doesn’t support Mac OS Because Silverlight is a browser plug-in.2 doesn’t separate out the Mac OS X versions.

5 Designer/Developer work distribution Licensed to SEB Link A/S . the tools and technologies involved in web-based software development have s Designer User Interface Developer Logic Data Sources User Interface Logic Figure 1.dk> .2 Why can’t we be friends? Traditionally.6 CHAPTER 1 Introducing Silverlight 1.Henrik Thiesen <henrik.thiesen@seb.

3. (Or is it Licensed to SEB Link A/S .dk> . For now.thiesen@seb. it’s important to understand that Developer Designer User Interface Logic Data Sources User Interface Logic Figure 1.Henrik Thiesen <henrik.NET.Why can’t we be friends? 7 The details of XAML are covered in section 1.6 Another Designer/ Developer work distribution viewpoint This figure clearly illustrates the breadth and depth of knowledge required by a Silverligh 1.1 The developer experience What makes the development experience in Silverlight so special? One word: .2.

this powerful version of the framework is backed by some of the ind 1.2 The designer experience Microsoft Expression Blend. is a professional design tool that empowers designers 1.8 CHAPTER 1 Introducing Silverlight As an additional bonus.thiesen@seb.dk> .Henrik Thiesen <henrik.2. or Blend.3 XAML The eXtensible Application Markup Language (XAML) is a declarative language that enables yo Licensed to SEB Link A/S .

Codebehind pages en Figure 1.7 Any object that you create in XAML can also be created within code.1 Code behind Much like ASP. XAML pages support the concept of code-behind pages.8 The relationship between an XAML file and a code-behind file within a C# project Licensed to SEB Link A/S .Henrik Thiesen <henrik.3.dk> .thiesen@seb.XAML 9 Figure 1. called behind the scenes. Also occurring behind the scenes is the executable code defined w 1.NET.

microsoft. These gr Snippet 1.Page" xmlns="http://schemas.3.cs file provides the variable and metho 1.thiesen@seb.1 A basic XAML file referencing two namespaces <UserControl x:Class="XAML01.dk> .com/winfx/2006/xaml/pres As this snippet illustrates. you’re permitted to summon multiple namespaces within a single XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik.10 CHAPTER 1 Introducing Silverlight automatically created by Visual Studio. The .2 Namespaces A namespace provides a way of organizing related objects within a common grouping.xaml.g.

dk> .microsoft. including custom elements.XAML ■ 11 http://schemas.com/winfx/2006/xaml/presentation namespace. referencing other elements. For this reason. Silverlight gives you the flexibility to Snippet 1. this namespace gener A tale of two namespaces In addition to the http://schemas. only re XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik.2 This example references a custom assembly called MyAssembly. the In addition to these two commonly used namespaces.dll that contains a <UserControl x:Class="XAML02.microsoft.com/winfx/2006/xaml/presentation—Provides ■ your applications with the core Silverlight elements.thiesen@seb.com/client/2007" xmlns:x As this snippet illustrates.Page" xmlns="http://schemas.microsoft.

as you can see.6 shows the relationship between XAML and .com/client The concept of a GradientBrush is discussed in chapter 8.dk> . but. you define t 1.3 A Grid with a gradient background <UserControl x:Class="CompoundProperties01.thiesen@seb.3 Compound properties Although the illustration in figure 1.3. 1.3.microsoft.Page" xmlns="http://schemas.12 CHAPTER 1 Introducing Silverlight XAML-related concepts that we should discuss—the least of which is the incredibly powerful compound property feature.NET types Snippet 1.4 Attached properties An attached property is a property specified within an element other than the element that XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik.

Henrik Thiesen <henrik.4 Blending it together Now that you have a fundamental understanding of the value that Silverlight brings to the w Walk-through 1.Top attached properties to position the Rectan 1.com/client This snippet uses the Canvas.4 An example showing the use of two attached properties in action <UserControl x:Class="AttachedProperties01. Select File > New > Project… From the New Project dial Licensed to SEB Link A/S .1 1 2 3 XAML Creating a Silverlight media experience in Visual Studio 2008 Launch Microsoft Visual Studio 2008.Page" xmlns="http://schemas.microsoft.thiesen@seb.Left and Canvas.dk> .Blending it together 13 Snippet 1.

the Page.thiesen@seb.com/winfx/2006/xaml/pre Licensed to SEB Link A/S . At this point. This dialog bo 6 7 Click OK. Once the Silverlight project is loaded within Visual Studio.Page" xmlns="http://schemas.microsoft. the Add Silverlight Application dialog box appears.dk> . O <UserControl x:Class="Welcome. enter the following project prop 5 Click OK.14 4 CHAPTER 1 Introducing Silverlight Once you’ve selected the Silverlight Application template.xaml file w <MediaElement x:Name="myMediaElement" Margin="20" Height="240" Width="320" Source="http://w This code segment uses a MediaElement object to reference a video file over the internet.Henrik Thiesen <henrik.

close the web-browser window tha In this walk-through. Blend will open the corresponding solution file.csproj file.silverlightinaction.5 Select Open Project… from the startup dialog box or F 5 If you attempt to open a .dk> .2 1 2 Matting a MediaElement using Expression Blend 2 3 4 Launch Microsoft Expression Blend 2.com/video1. After watching the video. you successfully created a Silverlight application that plays media r Walk-through 1.Henrik Thiesen <henrik.wmv" /> </Grid> </UserControl> 8 9 15 Press F5 to run the application.thiesen@seb.Blending it together Source="http://www. Licensed to SEB Link A/S .

Henrik Thiesen <henrik.thiesen@seb. drag the mouse down and to the right.dk> . The Rectangle From the upper-left corner. to ensure that this Rectangle provides a nice mat for the MediaElement.16 5 CHAPTER 1 Introducing Silverlight From the Toolbox along the left side of the Blend. Continue to drag until th 6 7 Next. set the Heigh Licensed to SEB Link A/S . select the Rectangle tool.

Henrik Thiesen <henrik.Blending it together 8 17 Manually set the Width and Height properties within the Layout category of the Properties p 9 10 Select the Brushes category. Select the Gradient Brush tab within the Brushes category and Licensed to SEB Link A/S .thiesen@seb.dk> .

If you were to r Licensed to SEB Link A/S .thiesen@seb. you have a Rectangle on top of the MediaElement. Set the value of thi Set the third and rightmost gradient stop to the same gray you used for the leftmost gradie 12 At this point. such as #FF383737. as shown i Add a new gradient stop by clicking the middle of the gradient slider. hiding it.18 11 CHAPTER 1 Introducing Silverlight Now fill the Rectangle with a gradient by doing the following: Click the leftmost gradient and set the value to a dark gray.dk> .Henrik Thiesen <henrik.

thiesen@seb. To do this. Close th This walk-through demonstrates how you can open Silverlight projects created from Visual St Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik. make sure the Rectangl 16 17 Press F5 to run the application.Blending it together 13 19 Select the [Rectangle] within the Objects and Timeline category within the Interaction pane 14 15 You need to place the Rectangle behind the MediaElement. Notice how this is consistent with Visual Studio.

Note that yo 3 4 5 6 7 8 Click Yes in this dialog box.3 1 2 Implementing the behavior of the video player in Visual Studio 2008 Either Alt-Tab back to Microsoft Visual Studio. Note that the XAML code is automatically updated to include t myMediaElement.MouseLeftButtonUp += new MouseButtonEventHandler(myMediaElement_MouseLeftBut 9 After this line of code is added.dk> . MouseButtonEventArgs e) { if (myMedia 11 Press F5 to run the application.thiesen@seb. Licensed to SEB Link A/S . or select it from the taskbar.20 CHAPTER 1 Introducing Silverlight Walk-through 1. the Page constructor should look like the following: public Page() { InitializeComponent(). myMediaElement.Henrik Thiesen <henrik.MouseLeftButtonUp += new MouseButtonE 10 Implement the following event handler: void myMediaElement_MouseLeftButtonUp( object sender.

you’ve successfully created a basic media player that illustrates many of th 1.Henrik Thiesen <henrik. cross-browser.thiesen@seb.dk> .5 Summary Silverlight is Microsoft’s offering for delivering rich. cross-platform user Licensed to SEB Link A/S .Summary 21 At this point.

we introduced Silverlight 2 and discussed the productivity and perfor 22 Licensed to SEB Link A/S .Henrik Thiesen <henrik.Harmony with the web This chapter covers ■ ■ ■ Creating a Silverlight control The Silverlight Application Model Managing the HTML DOM with Throughout chapter 1.thiesen@seb.dk> .

1 The relationship between Silverlight and the HTML DOM As mentioned in chapter 1. Silverlight is a browser-based plug-in. The shaded areas represent Silverlight appl Licensed to SEB Link A/S . This plug-in was designe Figure 2. let’s look at the relatio 2.The relationship between Silverlight and the HTML DOM 23 topic also covered in this chapter.1 Two theoretical uses of Silverlight. Before we can do any of this.Henrik Thiesen <henrik.dk> .thiesen@seb.

thiesen@seb.1. The lightly shaded area represen 2.” W3Schools Online Web Tutorials.co Licensed to SEB Link A/S . http://www.2 The darkly shaded area represents the HTML DOM.w3schools. As illustrated 1 Refsnes Data.Henrik Thiesen <henrik.dk> . “W3C DOM Activities.1 The HTML Document Object Model The HTML DOM enables you to easily access and manage content in a web page.24 CHAPTER 2 Harmony with the web Figure 2.

1.1.thiesen@seb.2 The Silverlight plug-in The Silverlight plug-in is a lightweight browser plug-in responsible for rendering Silverli 2.1 The DOM variants supported by Silverlight Browser(s) Internet Explorer Descriptio 25 Specification DHTML Object Model Gecko DOM Firefox Mozilla Netscape Safari one of the Silverlight-supported DOM variants.Henrik Thiesen <henrik. This tree str Licensed to SEB Link A/S . These DOM variants and their descriptions ar 2.The relationship between Silverlight and the HTML DOM Table 2.dk> .3 The Silverlight Object Model The Silverlight Object Model is represented as a hierarchical tree structure.

Web. This plugi 2 The Silverlight server control is part of the System.thiesen@seb. each child is rendered from l 2. This ass Licensed to SEB Link A/S .3 The order in which the Silverlight Object Model renders content The rendering process begins at the root element.dll assembly.2 Creating a Silverlight plug-in The goal of creating a Silverlight plug-in is to host a Silverlight application.Silverlight.dk> .Henrik Thiesen <henrik. From there.26 CHAPTER 2 Harmony with the web Figure 2.

Creating a Silverlight plug-in 27

use. But we’re going to discuss the specifics of a Silverlight plug-in while covering anoth 2.2.1

The Silverlight utility file: Silverlight.js The Silverlight.js utility file is part of the free Silverlight 2 SDK. This SDK is availabl REFERENCING THE SILVERLIGHT.JS FILE

Referencing the Silverlight.js file is as easy as referencing any other script file. The Si Snippet 2.1 Referencing the Silverlight.js utility file

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>My Silverlight Project</title> H B

You gain the ability to create a Silverlight plug-in by adding one line of code B. This sin 3

Microsoft periodically releases new versions of the Silverlight.js file. To facilitate dist Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

28 CHAPTER 2 Harmony with the web THE FUNCTIONS OF THE SILVERLIGHT.JS FILE

The Silverlight.js file exposes a number of valuable functions. These functions give you th Table 2.2 The primary utility functions exposed through the Silverlight.js utility file Fun Function name buildPromptHTML createObject createObjectEx HtmlAttributeEncode

These methods provide a powerful arsenal of options to help deliver the appropriate experie 2.2.2

Creating an instance of the Silverlight plug-in To initialize and create a Silverlight plug-in, you use one of two utility functions: creat 4 For a JSON tutorial, see www.json.org. Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Integrating a Silverlight plug-in 29

element, you call the createObjectEx method to add a Silverlight control, as a child, to th Snippet 2.2 Instantiating the Silverlight control

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>My Silverlight Project</title> < B C

This snippet demonstrates the two main steps of creating a Silverlight plug-in. The first s 2.3

Integrating a Silverlight plug-in Once you’ve decided to create a Silverlight plug-in, you must ensure it integrates nicely w ■ ■ Relate your Silverlight application to the HTML DOM Clarify the initial experience Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

30 ■ ■ CHAPTER 2 Harmony with the web Handle plug-in events Send initialization parameters

These general tasks cover quite a bit of ground, but we’re going to dive into the details t 2.3.1

Relating the Silverlight application to the HTML DOM The first three parameters of createObjectEx function build the relationship between a Silv SOURCE

The source parameter specifies the URI of the Silverlight content that should be loaded. Th Table 2.3 The three approaches for referencing a Silverlight application File extension .xa Approach Packaged Loose Inline * Assume this is part of a createObjectEx call.

We aren’t discussing the loose and inline approaches in detail because the packaged approac 5 Pronounced as zap Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Integrating a Silverlight plug-in PARENTELEMENT 31

The parentElement parameter specifies the HTML object that hosts the Silverlight plug-in. I ID

The unique identifier of the Silverlight plug-in is specified by the third parameter of the

Embedding Silverlight into a web page You may choose to explicitly create the object tag that hosts your Silverlight application. <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>My Silverlight Pro

In general, the properties specific to the Silverlight plug-in can be set through the param Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

32 CHAPTER 2 Harmony with the web parameter is the primary hook from the HTML DOM to the Silverlight plug-in. You can easily 2.3.2

Clarifying the initial experience While a Silverlight plug-in is being initialized, a number of properties clarify how that p Snippet 2.3 The initialization properties used by createObjectEx

Silverlight.createObjectEx({ source: "ClientBin/MySilverlightApp.xap", parentElement: docum HTML B

These properties B can be used to define an initial experience. (All the properties in snip HEIGHT AND WIDTH

The height and width properties specify the boundaries of the rectangular region that the S Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Integrating a Silverlight plug-in 33

Snippet 2.4 The Silverlight plug-in on the left uses absolute sizing by specifying pixel va Silverlight.createObjectEx({ source: "ClientBin/ MySilverlightApp.xap", Absolute sizing par BACKGROUND AND ISWINDOWLESS

The background property allows you to specify the color of the rectangular region where the Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

34 CHAPTER 2 Harmony with the web background: null, isWindowless: “false” background: “silver”, isWindowless: “true” background: “transparent”, isWindowless: “false” background: ”transparent”, isWindowless: “true”

Figure 2.4 The consequences of various background and isWindowless property combinations. T

setting the background property to transparent is only half the battle. The fourth image sh FRAMERATE

The frameRate property enables you to determine the maximum number of frames you want to re VERSION

When instantiating a Silverlight plug-in, you need to set the version property in the creat Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Integrating a Silverlight plug-in 35 Figure 2.Henrik Thiesen <henrik.6 The Silverlight Configuration dialog box.dk> .thiesen@seb. This dialog box is accessible by right IGNOREBROWSERVER The ignoreBrowserVer option empowers you to specify whether or not you should check to see ENABLEHTMLACCESS The final Boolean-based property in the Silverlight plug-in initialization provides you wit Licensed to SEB Link A/S .

we’ve covered all of the items that are required to create an instance of th Snippet 2.5 Registering events associated with a plug-in instance Silverlight.createObjectEx({ source: "ClientBin/MySilverlightApp.3 Handling plug-in events At this point. I ONLOAD The onLoad event occurs immediately after your Silverlight application has been loaded. By Licensed to SEB Link A/S .36 CHAPTER 2 Harmony with the web Matt could’ve easily avoided this time-bomb embarrassment by explicitly setting the enableH 2.thiesen@seb.xap".dk> .Henrik Thiesen <henrik.3. parentElement: docum HTML B This snippet shows how to wire up the two events associated with a Silverlight plug-in B.

} This snippet shows an all-purpose onError event handler. Regardless of how you in Snippet 2. } This snippet shows an extremely basic onLoad event handler. The event handler can be used to g Licensed to SEB Link A/S .Henrik Thiesen <henrik.").Integrating a Silverlight plug-in 37 the option of creating an event handler for when this event fires.4 The parameters of the onLoad event handler Description This value is a handle to Parameter sender context source In addition to the parameters of this event. you should know that there are times when this ONERROR The onError event is triggered when an exception hasn’t been handled in your application.dk> .thiesen@seb. source) { alert("loaded"). W Snippet 2.6 JavaScript A sample Silverlight plug-in onLoad event handler function plugin_Load(sender. context. errorArgs) { alert("An unexpected error has occurred.7 JavaScript A sample Silverlight plug-in onError event handler function plugin_Error(sender. This event handler shows the th Table 2.

dk> .8 Registering initialization parameters with a plug-in instance Silverlight.createObjectEx({ source: "ClientBin/MySilverlightApp. parentElement: docum HTML Licensed to SEB Link A/S . These properties are listed and described in table Table 2.NET application.4 Sending initialization parameters A Silverlight application is a lot like any other . imagine Snippet 2.xap". This parameter is a val 2. As an example. The second parameter.thiesen@seb.Henrik Thiesen <henrik.3.38 CHAPTER 2 Harmony with the web sender argument will represent the plug-in where the error occurred.5 The properties associated with the errorArgs parameter Description A numeric code Property ErrorCode ErrorMessage ErrorType Name You can learn a lot about an error through the errorArgs parameter. variety of publicly visible properties.

Eac INITPARAMS The initParams parameter empowers you to send any number of user-defined.Henrik Thiesen <henrik.thiesen@seb.dk> . keyvalue pairs to CONTEXT The context parameter gives you a way to uniquely identify a Silverlight plug-in.4 The Silverlight Application Model At this point.The Silverlight Application Model HTML initParams: "key1=value1. key2=123. you should have a firm understanding of how to add a Silverlight plug-in to Licensed to SEB Link A/S . context: "27d3b786-4e0c-4ae2-97a3-ce 39 B C This snippet demonstrates the basic usage of the initParams B and context C parameters. This plug 2. keyX=valueY".

com/client/2007/deployment" xmlns:x="http://sch XML B C D E This snippet shows a basic manifest file.9 A sample manifest file in XML <Deployment xmlns="http://schemas.4.40 CHAPTER 2 Harmony with the web loading a Silverlight application into that plugin. this application will g 2.Henrik Thiesen <henrik.xaml is generated during project compilation based on settings found in the pro Licensed to SEB Link A/S . which uses the EntryPointAssembly and EntryPointT 6 AppManifest.microsoft.thiesen@seb.1 The manifest file The manifest file is responsible for describing the Silverlight application to the Silverli Snippet 2. As you learned.dk> .

The Silverlight Application Model 41 2.dk> . the Startup event fires.Henrik Thiesen <henrik.4. this event loads Snippet 2. By default.thiesen@seb. This object is defined MANAGING THE START OF A SILVERLIGHT APPLICATION Once the App object has been created. StartupEventArgs e) { IDictionary<string.10 A sample Startup event handler private void Application_Startup(object sender.2 The Silverlight application The entry point into the Silverlight application is the App object. s B C C# D This particular event handler shows how to parse the initParams that may have been passed i Licensed to SEB Link A/S .

Henrik Thiesen <henrik.UnhandledException event empowers you to handle uncaught exceptions. so le HANDLING UNFORESEEN ERRORS The Application.thiesen@seb. And at this point. a Silverlight application will be visible to your users. Any Ex Snippet 2.Exit event is the last thing that occurs before an application is shut down ■ ■ ■ ■ The user closes the browser window.11 A sample UnhandledException event handler private void Application_UnhandledException(object sender. The event handler uses an argu EXITING THE SILVERLIGHT APPLICATION The Application.dk> . The user closes the browser tab that the Silverlight ap Licensed to SEB Link A/S .42 CHAPTER 2 Harmony with the web rendered. ApplicationUnhandledExceptionEve C# B C D This snippet shows a basic UnhandledException event handler.

6 The properties of the SilverlightHost object Description Retrieves the background Property Background Content IsLoaded Settings Source This table shows the properties available through the SilverlightHost object. SilverlightHost host = application. B C This snippet shows how to retrieve the settings associated with a hosting plug-in.thiesen@seb.Henrik Thiesen <henrik.dk> .Current.Host. The firs Table 2.The Silverlight Application Model 43 This event doesn’t have any special event handling parameters like the Startup and Unhandle READING PLUG-IN SETTINGS Once the Silverlight application has been loaded. you can retrieve information about the ho Snippet 2.12 Retrieving settings associated with hosting plug-in C# Application application = Application. These propert Licensed to SEB Link A/S .

Browser namespace is a special feature of the Silverlight API. NOTE The System.dk> .5 Interacting with the HTML DOM At this point.Browser namespace exposes a number of classes that encapsulate the featu 2.Henrik Thiesen <henrik.Windows. you should have a basic understanding of what a Silverlight application is.4. Th 2.Windows.1 Managing the web page from managed code The HtmlPage object exposes a property called Document. This name The System.5.44 CHAPTER 2 Harmony with the web 2.thiesen@seb. This property is an HtmlDocument ob Licensed to SEB Link A/S .3 Application dependencies The application dependencies are the items that your application needs to run correctly.

the Table 2.13 Referencing an HTML element via managed code C# HtmlDocument document = HtmlPage.8 The navigation methods of an HtmlDocument Method GetElementById Description Empow GetElementsByTagName This table introduces the powerful and often used GetElementById and GetElementsByTagName m Snippet 2. HtmlElement element = document.GetElementById Note that the “myDiv” element is simply an HTML DIV element within the HTML page hosting th Licensed to SEB Link A/S . NAVIGATING WEB PAGE CONTENTS The HtmlDocument gives you two entry points into the currently loaded document.thiesen@seb.7 The entry points into the HtmlDocument Description This property represents the r Property DocumentElement Body These properties represent great ways to enter into an HtmlDocument. These entry Table 2.Henrik Thiesen <henrik.Document. More specifically.dk> . The Silverlight version gives you the ability to do all this from managed code.Interacting with the HTML DOM 45 tionality.

HtmlElement myTextField = document. Some of these prop Snippet 2. Note that this Licensed to SEB Link A/S .14 Using the GetProperty and SetProperty methods HtmlDocument document = HtmlPage.9 CHAPTER 2 Harmony with the web The navigation properties of an HtmlElement Description A collection of items hosted by the Property Children CssClass Id Parent TagName This wrapper exposes several properties that empower you to interact with an element from m WORKING WITH ELEMENT PROPERTIES Each element in the HTML DOM exposes a number of descriptive properties.dk> .46 Table 2.Henrik Thiesen <henrik.Document.GetElementByI C# B C This snippet shows how the GetProperty and SetProperty methods can be used.thiesen@seb.

dk> .GetElementById("myD B This snippet shows how to use a style attribute from managed code.15 Assigning a style attribute from managed code HtmlDocument document = HtmlPage. HtmlElement myDiv = document.Interacting with the HTML DOM 47 The GetProperty method takes a string that represents the name of the property value to ret HANDLING CSS INFORMATION Elements within the HTML DOM are designed to separate content from presentation. The first step is to ret ACCESSING THE QUERY STRING One of the common approaches for managing state in a web application involves using the que Licensed to SEB Link A/S . The presen Snippet 2.Document.thiesen@seb.Henrik Thiesen <henrik.

Notice that.8 The elements of a web address This figure shows the breakdown of a web address. HtmlDocument document = HtmlPage.Document.Henrik Thiesen <henrik.2 Working with the user’s browser window The hosting browser window is represented as an HtmlWindow object.5. This object can’t be ins Snippet 2. foreach (st This snippet shows how to retrieve the individual key/value pairs of a QueryString. significantly.Window. the QueryStri Snippet 2.48 CHAPTER 2 Harmony with the web the query box. and wait for the results.dk> . Note th 2.thiesen@seb.Window. This simpler approach is made possible through the Figure 2.16 Showing the pairs of the QueryString HtmlWindow window = HtmlPage. Licensed to SEB Link A/S .17 C# C# Retrieving in-memory representation of hosting browser window in C# HtmlWindow window = HtmlPage.

It’s important to n Table 2.Window.thiesen@seb.Henrik Thiesen <henrik.Interacting with the HTML DOM 49 This snippet demonstrates how to retrieve the hosting browser window. Note how easy it is to deliver an HTML prompt to a user. window. It’s also important to note that t NAVIGATING THE BROWSER WINDOW Navigation is an important part of any web application. There may be times where you want t Licensed to SEB Link A/S .dk> .Alert("Welcome!"). Snippet 2.10 The prompt options available through the HtmlWindow class Description Shows a si Method Alert(…) Confirm(…) Prompt(…) These prompt options mimic the prompt choices available through the HTML DOM Window object.18 Displaying an alert to a user C# HtmlWindow window = HtmlPage. which can be used to PROMPTING THE USER The HtmlWindow class enables you to deliver HTML prompts to your users.

These two options are shown in table 2.silverlightinaction.11 CHAPTER 2 Harmony with the web The navigation options available through the HtmlWindow class Method Description This metho Navigate(…) NavigateToBookmark(…) two methods that can be used to get the job done.11 Snippet 2.Windo B C One of the key items to notice from this snippet is the fact that you must always use a Uri DISCOVERING THE BROWSER PROPERTIES The statically visible BrowserInformation property exposes detailed statistics about a user Table 2.thiesen@seb.dk> .com").19 Launching the official Silverlight 2 in Action website in a new browser window Uri uri = new Uri("http://www.Henrik Thiesen <henrik.12 properties Descriptions of the BrowserInformation properties and their correspon BrowserInformation BrowserVersion Navigator appVersion Description Represents the platform and version associated with the browser.50 Table 2. Specifies whet CookiesEnabled cookieEnabled Licensed to SEB Link A/S . HtmlWindow window = HtmlPage.

Interacting with the HTML DOM 51 Table 2.12 Descriptions of the BrowserInformation properties and their corresponding Naviga Based on these options. This snippet shows how you can retrieve the statistics associated with a user’s browser. you can see that you have access to a lot of valuable information. Snippet 2.20 Displaying the name of the user’s browser BrowserInformation browserInfo = HtmlPage.BrowserInformation.thiesen@seb. CALLING MANAGED CODE FROM JAVASCRIPT Calling managed code from JavaScript is a fairly simple process.5.dk> .3 Bridging the scripting and managed code worlds For anyone who has endured the mind-numbing nuisance of parsing XML content via JavaScript.Henrik Thiesen <henrik. This process includes thre Licensed to SEB Link A/S . Th 2. HtmlWindow window = HtmlPage.

22 Exposing a managed code item to the scripting world [ScriptableMember] public void ExecuteWebService() { // Make a call to a web service } This snippet shows the basic usage of the ScriptableMember attribute.52 CHAPTER 2 Harmony with the web Once these tasks have been performed.dk> .21 Preparing a type for scripting C# C# C# [ScriptableType] public partial class Page : UserControl This snippet shows how to make a type accessible to JavaScript by exposing the default Silv Snippet 2. you’re free to reference the managed elements from Ja Snippet 2.Henrik Thiesen <henrik. Licensed to SEB Link A/S . This attribute gives Snippet 2.23 Exposing an object to the scripting world public Page() { InitializeComponent().thiesen@seb.

dk> .w3.Interacting with the HTML DOM C# HtmlPage.24 Referencing a managed item from the scripting world <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml JavaScript Licensed to SEB Link A/S . This meth Snippet 2.Henrik Thiesen <henrik. } 53 This snippet demonstrates the basic usage of the RegisterScriptableObject method.RegisterScriptableObject("bridge". this).thiesen@seb.0 Transitional//EN" "http:// www.

Window. new object[]{}). USING JAVASCRIPT FROM MANAGED CODE Silverlight gives you the flexibility to call JavaScript from managed code. including your Silverlight application Licensed to SEB Link A/S .54 CHAPTER 2 Harmony with the web This snippet demonstrates how a scriptable object can be accessed from a plug-in instance.thiesen@seb. th Snippet 2.dk> .Henrik Thiesen <henrik. This code can be used to print the current web page. and in turn.Invoke("print".25 Calling JavaScript object’s function from managed code C# HtmlWindow window = HtmlPage. window.

dk> . This Licensed to SEB Link A/S .6 Summary Silverlight was designed to be consistent with the well-established web architecture.Henrik Thiesen <henrik.thiesen@seb.Summary USING JAVASCRIPT TO COMMUNICATE BETWEEN SILVERLIGHT PLUG-INS 55 Silverlight plug-ins are standalone and oblivious to other Silverlight plug-ins running on 2.

Henrik Thiesen <henrik.dk> . you learned about Silverlight’s tight integration with the well-established w 56 Licensed to SEB Link A/S .thiesen@seb.Back to the basics: Layout and text This chapter covers ■ ■ ■ Layout basics Text features Core Silverlight UI features In chapter 2.

A Canvas for your imagination 57 layout panels. Silverlight" /> </Canvas> B This snippet shows a basic Canvas with a small amount of content B.1 A Canvas for your imagination Envision a painter inspired to re-create a mountainous landscape. a tre Snippet 3. we’ll shift our focus to another stapl 3.Henrik Thiesen <henrik.dk> . Result XAML Hello.2 A basic Canvas with some content.1 XAML A basic Canvas element. The content of a Canvas Licensed to SEB Link A/S . As you can imagine. Silverlight <Canvas> <TextBlock Text="Hello. This serves as a great example Snippet 3. After discussing these layout panels.thiesen@seb. In this case the content is TextBlock. <Canvas Height="200" Width="300" Background="White"> </Canvas> This snippet shows an empty Canvas with a white background.

this approach place Snippet 3. But.1.GetLeft(tb) + 15.SetLeft(tb. The first SETTING THE OFFSETS By default.4 Changing the position of an element at runtime C# double newLeft = Canvas. the content within a Canvas is automatically arranged. double newTop = Canv B C This snippet shows how the GetLeft and SetLeft methods are used to move a TextBlock 15 pixe Licensed to SEB Link A/S .Henrik Thiesen <henrik.Top="30" /> The TextBlock uses the Left and Top attached properties to set its position within an imagi Snippet 3.thiesen@seb.Left="20" Canvas.1 Arranging content of a Canvas You can arrange content within a Canvas by using at least one of two approaches.3 properties XAML A basic TextBlock using the Canvas element Left and Top attached <TextBlock x:Name="tb" Text="Hello" Canvas. Canvas. newLeft).58 CHAPTER 3 Back to the basics: Layout and text 3.dk> .

Henrik Thiesen <henrik.thiesen@seb.ZIndex="2" Width="60" Height="60" Backgr XAML Licensed to SEB Link A/S .6 Result Using the ZIndex to move an element into the foreground <Canvas> <Canvas x:Name="myCanvas"> <Canvas Canvas.A Canvas for your imagination 59 you may inadvertently overlap the content within a Canvas.dk> . Although this overlapping effect SETTING THE STACK ORDER By default. T TIP XAML You may want to use a Canvas inside another one of the layout options discussed later becau You can change the ZIndex value to a value greater than 0 to move the Canvas farther into t Snippet 3. when content is rendered within a layout panel.5 Result The default stacking order of elements <Canvas Width="180" Height="180" /> <Canvas Width="60" Height="60" Background="LightGray"/> This snippet shows the default stacking approach used when rendering overlapping content. each element is rendered on its Snippet 3.

GetZIndex(myElement) + 10. In addition to sett Snippet 3.60 CHAPTER 3 Back to the basics: Layout and text This snippet shows the effects of setting the ZIndex attached property.Henrik Thiesen <henrik. This snippet shows how to move an element further into the foreground of a Canvas. The process of determining Licensed to SEB Link A/S .1.7 C# Changing the position of an element at runtime int newZIndex = Canvas.thiesen@seb.dk> . You add 3. newZIndex).SetZIndex(myElement.2 The Canvas: packing a punch One of the areas where the Canvas packs a punch is performance. Canvas.

8 Result A basic StackPanel with three elements <StackPanel> <Canvas Width="90" Height="30" Background="Red"/> <Canvas Width="90" Height="3 As this snippet displays. after I (Chad) awoke this morning.1 illustrates the different text lengths assoc 3. elements within a StackPanel are rendered one after another from XAML Licensed to SEB Link A/S .thiesen@seb.dk> .The StackPanel: Stack ’em deep 61 the Welcome text to other languages.Henrik Thiesen <henrik. Table 3. I found myself immersed in a fun-filled cros Snippet 3.2 The StackPanel: Stack ’em deep Personally.

shifting the layout from a vertical to horizontal orientati Item # 1 2 3 Description Lollipops Gum Price $0.Henrik Thiesen <henrik.dk> .25 $0.03 Figure 3.3 The power Grid The Grid panel gives you the ability to easily lay out content in a tabular format.2 A basic purchase order Imagine attempting to re-create the purchase order shown in this figure using a series of S 3.25 XAML Candy Beans $0.thiesen@seb.9 Result A basic StackPanel that uses a Horizontal Orientation <StackPanel Orientation="Horizontal"> <Canvas Width="90" Height="30" Background="Red"/> <Ca As you can see in this snippet. This ta Licensed to SEB Link A/S .62 CHAPTER 3 Back to the basics: Layout and text Snippet 3.37 Quantity 5 4 27 Total Total $1.

3.Henrik Thiesen <henrik. this element generally se Snippet 3.thiesen@seb.dk> . As you’d expect.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowD E F This snippet defines a Grid with three columns D and three rows F. The rows and columns of 3.The power Grid 63 defined within the ColumnDefinitions collection.1 Arranging Grid content The content of a Grid consists of the elements that you want to arrange in a tabular fashio Licensed to SEB Link A/S .10 The basic syntax of a Grid Result XAML <Grid x:Name="myGrid" ShowGridLines="True" Height="120" Width="120" Background="LightGray"> B C D <Grid.

64 CHAPTER 3 Back to the basics: Layout and text how to arrange content in a Grid. The proper Licensed to SEB Link A/S . which will be used to create a basic input form (snippet Snippet 3.Row="1"></TextBox> <TextBox Width="150" Grid.dk> . These two a Snippet 3.Henrik Thiesen <henrik.11 Arranging content within a Grid Result <Grid x:Name="myGrid" ShowGridLines="True" Background="LightGray" Width="310" Height B C <TextBox Width="150" Grid.Colu This snippet shows a basic input screen that uses a Grid to arrange its content. This conte POSITIONING GRID CONTENT Positioning content within a Grid is handled mainly by two attached properties.Row="3" Grid.thiesen@seb.Column="2" /> This line of XAML illustrates how to use the Row and Column attached properties.Column="1" Grid.12 The basic syntax of the Column and Row attached properties XAML <TextBlock Text="Rock On!" Grid.

Oc 3.13 The syntax of the ColumnSpan and RowSpan attached properties XAML <TextBox Grid. the element will SPANNING CELLS Occasionally.dk> .3.thiesen@seb.2 Sizing it up The overall dimensions of a Grid can be set to a specific number of pixels through the Heig Licensed to SEB Link A/S .RowSpan="1" Grid. you run into situations where you need to allow content to span multiple cell Snippet 3.Column="1" Grid.Row="1" Grid.Henrik Thiesen <henrik.ColumnSpan="2" /> The ColumnSpan and RowSpan properties are easy to add to any piece of content in a Grid.The power Grid 65 If you attempt to assign an element to a row or column that doesn’t exist.

dk> .66 CHAPTER 3 Back to the basics: Layout and text approach. But first. Licensed to SEB Link A/S .thiesen@seb.14 A basic Grid using star sizing. Absolute sizing AUTOMAGICALLY The Auto GridLength option automatically determines how large or small to make an element.Henrik Thiesen <henrik. Result <Grid x:Name="myGrid" ShowGridLines="True" Background="LightGray" Width="200" Height B XAML C This snippet shows a Grid using star sizing in addition to absolute sizing. we’ll cover the default option used for sizing rows and columns: star WISH UPON A STAR Star sizing enables you to equally distribute the available area of a Grid across its rows Snippet 3.

Henrik Thiesen <henrik.The power Grid 67 Snippet 3.16 A Grid using absolute sizing Result <Grid x:Name="myGrid" Height="100" Width="300" ShowGridLines="True" Background="Ligh Licensed to SEB Link A/S .15 A basic Grid using auto sizing Result <Grid x:Name="myGrid" Height="100" Width="300" ShowGridLines="True" Background="Ligh B XAML C This snippet uses the Auto sizing approach for the Grid’s columns B and rows C. The result ABSOLUTE The final approach for allocating the available area to a row or column involves using a do Snippet 3.thiesen@seb.dk> .

thiesen@seb.Henrik Thiesen <henrik.17 Programmatically adding a row and a column while setting the height and width // Programmatically add a Row RowDefinition myRow = new RowDefinition().3 Working with the Grid programmatically Usually. myGrid.dk> .RowDefinitions> <RowDefinition Height="68.3.5"></RowDefinition> <RowDefinition Height=" B This snippet shows the absolute sizing approach in action.RowDefiniti C# B // Programmatically add a Column ColumnDefinition myColumn = new ColumnDefinition(). This approac ADDING ROWS AND COLUMNS AT RUNTIME Adding rows or columns programmatically at runtime is as simple as writing two lines of cod Snippet 3. The rows use a double-precision 3.68 CHAPTER 3 Back to the basics: Layout and text XAML <Grid. the rows and columns of a Grid are created at design time using XAML. myGrid C Licensed to SEB Link A/S .

The power Grid 69 This snippet adds a row and a column to the Grid created in snippet 3.Henrik Thiesen <henrik.18 Programmatically removing a row and a column // Programmatically remove the first Row RowDefinition myRow = myGrid.ColumnDefinitions. 3. my C# B // Programmatically remove the last Column int lastColumnIndex = myGrid.3.4 Customizing cell boundaries Silverlight provides a way to customize the cell boundaries of a Grid that’s similar to the Licensed to SEB Link A/S .C C This snippet shows two methods for programmatically removing rows and columns from a Grid. you must use one of two approaches.RowDefinitions[0].thiesen@seb.dk> . The first approac REMOVING ROWS AND COLUMNS AT RUNTIME To remove either a row or a column from a Grid. These a Snippet 3.16.

microsoft.thiesen@seb.xap. Significantly. which include the GridSplitter. increasing the size of the . This divider can be used to style the bou Licensed to SEB Link A/S . this resizing process doesn’t change the dimensions of the overall Gri ACCESSING EXTENDED CONTROLS The extended controls.xap file by about 266 USING THE GRIDSPLITTER The GridSplitter defines a divider within a Grid.Windows. are part of an assembly called Syste Snippet 3.com/winfx/2006/xaml XAML B This snippet shows how to reference the extended controls assembly. WARNING Referencing the System.dk> .Page" xmlns="http://schemas.Controls assembly will cause it to be bundled with your application’s .19 Referencing the extended controls assembly <UserControl x:Class="Snippet3_19.70 CHAPTER 3 Back to the basics: Layout and text size.Henrik Thiesen <henrik.

RowDefinitions> <RowDefinit B <Canvas Background="Gray" Margin="10" Grid.thiesen@seb.Row="2" /> <Canvas Background="Gray" Margin="1 This snippet creates a 3-by-3 Grid that has two GridSplitter elements.Henrik Thiesen <henrik.dk> . The first GridSplitt Licensed to SEB Link A/S .Row="1" /> <Canvas Background="Silver" Margin="1 C <Canvas Background="Silver" Margin="10" Grid.The power Grid 71 Snippet 3.20 The basic syntax and usage of a GridSplitter Result XAML <Grid x:Name="LayoutRoot" Background="White"> <Grid.

21 A basic TextBlock in action Result <Canvas x:Name="LayoutRoot" Background="White"> <TextBlock x:Name="myTextBlock" Text B This snippet shows a basic way to include text within your Silverlight applications. and Silverlight is no exception. This p 3. These properti Licensed to SEB Link A/S .1 Font properties The TextBlock has five properties related to the styling of a selected font. Snippet 3.72 CHAPTER 3 Back to the basics: Layout and text In general.thiesen@seb.4. the Grid is the most powerful layout panel in Silverlight because it can do alm 3.Henrik Thiesen <henrik.4 Displaying text Text is an important part of any presentation technology.dk> .

3 A sampling of the font families supported within Silverlight Figure 3.3 shows the nine TrueType fonts supported within Silverlight.Displaying text Table 3.2 The font-related properties available in Silverlight and their CSS equivalents Te 73 CSS property name font-family font-size font-weight font-stretch font-style FONTFAMILY By default.dk> .thiesen@seb.Henrik Thiesen <henrik. In addition to these Licensed to SEB Link A/S . the TextBlock displays text using the Lucida Sans Unicode font on Windows machi Figure 3.

This heaviness is o FONTSTRETCH The FontStretch property gives you the ability to either condense or expand the font associ Licensed to SEB Link A/S .dk> . In addition to setting the FontSi FONTWEIGHT The FontWeight property represents the heaviness of the displayed text.) The FontSize property empowers you to se Snippet 3.74 FONTSIZE CHAPTER 3 Back to the basics: Layout and text n x 96 (n represents the number of points to use.22 Setting the FontSize at design time XAML <TextBlock Text="I’m a Big Boy Now.thiesen@seb." FontSize="32" /> This basic line of XAML sets the FontSize to a 24pt font.Henrik Thiesen <henrik.

FontStyle = FontStyles. This static proper Licensed to SEB Link A/S . Setting the FontStyle during ru Snippet 3.4 The acceptable values for the FontStretch property are listed under the Name colu tional web application. Notice how this snippet uses a FontStyles static property called Italic.thiesen@seb.Italic.24 Setting the FontStyle at runtime myTextBlock. But with Silverlight.Displaying text 75 Table 3.Henrik Thiesen <henrik.dk> .23 Setting the FontStyle at design time XAML C# <TextBlock x:Name="myTextBlock" Text="Going Italic" FontStyle="Italic" /> This snippet shows how to set the FontStyle at design time. you can stylize your text with this feature b FONTSTYLE The FontStyle property gives you the ability to switch the text of a TextBlock into italic Snippet 3.

2 Flow control The TextBlock enables you to control the overall flow of text through two nested elements.4.4.76 CHAPTER 3 Back to the basics: Layout and text styling of a TextBlock. Snippet 3. Licensed to SEB Link A/S .3 Text properties Silverlight gives you the ability to further customize your text through four useful proper FOREGROUND The Foreground property allows you to set the color of a block of text. More specifically.dk> .Henrik Thiesen <henrik.25 A TextBlock with Inline elements Result XAML <TextBlock Text="Scene 1: The Greeting" FontWeight="Bold" FontSize="17"> <LineB The conversation in this snippet shows one way to use the Run and LineBreak Inline elements 3.thiesen@seb. Silverlight goes beyond basic font styling and gives you the abilit 3.

dk>   .28 Wrapping text within a TextBlock This snippet shows how to change the TextWrapping property from its default value of NoWrap Licensed to SEB Link A/S . section 3.thiesen@seb.Henrik Thiesen <henrik.Displaying text 77 solid colors. For now Snippet 3.1) TEXTDECORATIONS The TextDecorations property gives you the ability to underline text. <TextBlock Text="I m Serious" TextDecorations="Underline" /> Much like the FontStyle property. the TextDecorations property has more options in WPF—the TEXTWRAPPING The TextWrapping property enables you to specify how text should wrap across multiple lines Snippet 3. The various Brush options are not covered until chapter 8.27 Underlining text in a TextBlock. This can be accomplis Snippet 3.26 Setting the Foreground of a TextBlock at design time XAML XAML Result <Canvas Width="200" Height="140"> <TextBlock Text="Eating a lot of fruit c This snippet changes a TextBlock from the default black SolidColorBrush (covered in 8.3.

These options provide one w 3.29 The Left.4 Spacing Spacing is effective for making text easier to read.30 The relationship between the FontSize and LineHeight properties Result XAML Licensed to SEB Link A/S . and Right TextAlignment options Result <Canvas Width="640" Height="480" Background="White"> <TextBlock Text="Everybody to t This snippet demonstrates the invaluable TextAlignment options. You Snippet 3.4.Henrik Thiesen <henrik.78 TEXTALIGNMENT CHAPTER 3 Back to the basics: Layout and text The TextAlignment property gives you the ability to align the text within a TextBlock. This can help individuals with diminis LINEHEIGHT The LineHeight property determines the height of the bounding box that your text will be co Snippet 3.dk> .thiesen@seb. Center.

thiesen@seb.31 The effects of the Padding property on a TextBlock Result <StackPanel x:Name="myStackPanel" Background="LightGray"> <TextBlock Text="Give Me S This snippet shows how a Padding of 20.2 pixels creates a nice bubble around some text.Displaying text 79 <Canvas Height="450" Width="485"> <TextBlock Width="110" LineHeight="1" FontSize="14" TextW B As this snippet illustrates. the LineHeight property often alters the layout of wrapped tex PADDING The Padding property represents the amount of cushion to use within a TextBlock.dk> .Henrik Thiesen <henrik. You XAML XAML Licensed to SEB Link A/S . This space Snippet 3.

as well as the inva 3.1 Properties The UIElement and FrameworkElement classes expose a number of valuable and interesting prop XAML <StackPanel Background="LightGray"> <TextBlock Text="HELLO" Padding="3.80 CHAPTER 3 Back to the basics: Layout and text Snippet 3.Henrik Thiesen <henrik. This list o 3.12"></TextBl Licensed to SEB Link A/S . you’ve seen a variety of layout Panel options.5 The UIElement and FrameworkElement Throughout this chapter.6.5.thiesen@seb.9.dk> .7.5.32 A more granular way to use the Padding property Result This snippet shows the Padding property using a comma-delimited list of values.

By default.dk> .33 Setting the Cursor of a FrameworkElement at design time XAML <Canvas Cursor="Hand" Background="Green" Height="60" Width="180"> <TextBox Cursor="Sty This snippet uses two non-default cursor options.The UIElement and FrameworkElement 81 enhance your applications in new ways.5 An example of the Opacity property Licensed to SEB Link A/S .Henrik Thiesen <henrik.thiesen@seb.5 The Cursor elements These optio OPACITY The Opacity property represents the transparency of an element. the cursor will change to i Snippet 3. this double-pre Figure 3. Table 3. Because of the abstract nature of the UIElement and CURSOR When a user navigates the mouse cursor over a FrameworkElement.

34 A StackPanel with three Visible UIElement items Result <StackPanel x:Name="myStackPanel" <TextBox x:Name="tb1" Width="60" <TextBox x:Name=" Background="Orange" Width="90"> Background="LightGray" /> Background="DarkGray" /> Backgrou This snippet shows three TextBox elements.thiesen@seb. By default. each of these elements has a Visibil Snippet 3.Henrik Thiesen <henrik.dk> . The TextBox with the name tb2 isn’t shown TAG! YOU’RE IT The Tag property gives you the ability to store an in-memory object within a FrameworkEleme Licensed to SEB Link A/S .35 A StackPanel with a Collapsed UIElement Result <StackPanel x:Name="myStackPanel" <TextBox x:Name="tb1" Width="60" <TextBox x:Name=" XAML XAML Background="Orange" Width="90"> Background="LightGray" /> Background="DarkGray" Background= This snippet highlights the effects of Collapsed.82 VISIBILITY CHAPTER 3 Back to the basics: Layout and text The Visibility property gives you the ability to toggle whether or not a UIElement can be s Snippet 3.

Henrik Thiesen <henrik. This grid contain This figure shows a common feature found in almost any web application. Within an applicati HORIZONTALALIGNMENT AND VERTICALALIGNMENT Every FrameworkElement gives you the opportunity to specify how it should be aligned within Licensed to SEB Link A/S .dk> .The UIElement and FrameworkElement 83 Figure 3.thiesen@seb.6 The figure on the left represents a page that displays a grid.

Henrik Thiesen <henrik. the lighter area represents the Padding Result <StackPanel Background="Gray"> <TextBox Background="LightGray" Margin="10" Padding=" Licensed to SEB Link A/S .84 CHAPTER 3 Back to the basics: Layout and text Snippet 3.37 The darker area represents the Margin.36 Demonstrating the various VerticalAlignment and HoriztonalAlignment options Result <StackPanel Orientation="Horizontal"> <StackPanel Width="200" Background="LightGray" B XAML C This snippet shows the effects of all four HorizontalAlignment B options and all four Verti MARGIN Similar in nature to the Padding property. the Margin property enables you to specify a cus Snippet 3.dk> .thiesen@seb.

dk> .38 Moving a TextBlock 5 pixels at a time by using the GetValue and SetValue metho <Canvas x:Name="parentCanvas" Width="400" Height="400" Background="LightGray"> <TextBlock x B private void MyTextBlock_Click(object sender.5. This may cause a bit 3.thiesen@seb.2 Methods Two common tasks are often performed during runtime. A DependencyObject gives you the ability to Snippet 3. The first task involves managing attac MANAGING ATTACHED PROPERTIES Every UIElement represents a DependencyObject.Henrik Thiesen <henrik.The UIElement and FrameworkElement 85 This snippet shows the Margin and Padding properties working together. MouseButtonEventArgs e) { double top = Conver C# C D Licensed to SEB Link A/S .

This is made FINDING ELEMENTS As described in chapter 2.86 CHAPTER 3 Back to the basics: Layout and text When a TextBlock is clicked B.dk> .thiesen@seb.Henrik Thiesen <henrik. Your user Licensed to SEB Link A/S . it will move five pixels down and to the right.6 Summary A rich and interactive user experience is primarily about presenting information. the Silverlight Object Model is represented as a hierarchical tr 3.

thiesen@seb.dk> . Stack Licensed to SEB Link A/S .Henrik Thiesen <henrik. Silverlight provides the Canvas. To help accomplish an orderly UI.Summary 87 in a pleasing way.

Handling user interaction This chapter covers ■ ■ ■ Mastering drag-and-drop implementations Learning about the control library Creating dialog Chapter 3 set the launchpad for your applications by covering the flexible layout model and 88 Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik.dk> .

1. it becomes the primary target for any information entered throug Snippet 4. if (silv Licensed to SEB Link A/S .1 Capturing the keyboard Have you ever considered how an application determines how to handle your keystrokes? Often UNDERSTANDING FOCUS When an element has focus.1 The JavaScript that gives focus to a Silverlight control so that it can accept JavaScript var silverlightControl = document.dk>     . These controls provide interesting features that will be us 4.1 Understanding device support Real-world applications need a way to accept input from users. This process of collecting i 4.Henrik Thiesen <henrik.getElementById( SilverlightControl ).Understanding device support 89 trols that don’t fit elsewhere.thiesen@seb.

2 A page in Silverlight that responds to the KeyDown and KeyUp events.90 CHAPTER 4 Handling user interaction This snippet uses the HTML DOM to manually give the focus to an instance of the Silverlight HANDLING KEYBOARD EVENTS Silverlight provides two events directly related to the keyboard.dk> . The event <UserControl x:Class="Keyboard01.Text = "Key (" + e.thiesen@seb.Henrik Thiesen <henrik.com/winfx/2006/xaml/ XAML B public partial class Page : UserControl { public Page() { InitializeComponent(). KeyEventArgs e) { myTextBlock. this. These events. The Licensed to SEB Link A/S .Key This snippet shows a page in Silverlight that responds to the KeyDown and KeyUp events. KeyDown and Snippet 4.microsoft.Page" xmlns="http://schemas.KeyUp C D private void Page_KeyUp(object sender.

Why would I ever DEALING WITH MODIFIER KEYS Modifier keys are those used in combination with other keys. the appropriat Table 4. you may be scratching your head and thinking.Henrik Thiesen <henrik. Regardless of the method.thiesen@seb.dk> .1 The properties of the KeyEventArgs class Description A bool that signals whether Property Handled Key PlatformKeyCode After reviewing this table. Modifier keys are necessary be Licensed to SEB Link A/S .Understanding device support 91 other approach uses traditional procedural code C.

thiesen@seb.dk> . KeyEventArgs e) { if (e.Henrik Thiesen <henrik.Key == Key. In addition to responding to button-r MOUSE EVENTS Silverlight supports a range of movement and click-related events emitted from the mouse.B) { if ((Keybo This snippet shows how you can go beyond individual key events in Silverlight. This ke Apple Control None Shift Windows Snippet 4.2 Option Alt CHAPTER 4 Handling user interaction The ModifierKeys available within Silverlight 2 Description Represents the Alt key. These events 4.3 A basic example using ModifierKeys private void Page_KeyDown(object sender.1.2 Trapping the mouse The mouse is slightly more complex than the keyboard.92 Table 4. T C# Licensed to SEB Link A/S .

thiesen@seb.4 lists the properties available through the MouseEventArgs class.Understanding device support Table 4.Henrik Thiesen <henrik.1 In order to be consistent across platforms.4 The properties exposed by the MouseEventArgs Description A bool that flags whethe Property Handled StylusDevice Table 4.dk> . As this table sh 1 2 OS X supports right-click context menus when using a single button mouse by holding the Ctr Licensed to SEB Link A/S . Silverlight 2 doesn Table 4.3 The click-related events associated with the mouse Event MouseLeftButtonDown Desc 93 MouseLeftButtonUp have a right mouse button.

Henrik Thiesen <henrik.thiesen@seb. Move the object to the new location.5 undoubtedly separate the mouse from the keyboard.dk> . These movement-re DRAG AND DROP Dragging and dropping visual components is an interactive experience that desktop users are 1 2 3 Select the object to drag. Release the object and drop The first step in the drag-and-drop process involves selecting the object to drag. In order Licensed to SEB Link A/S .5 Event MouseEnter MouseMove MouseLeave CHAPTER 4 Handling user interaction The mouse-movement-related event handlers Description Triggers when the user enters the bou The events in table 4.94 Table 4.

private Point lastPoint = new Point().thiesen@seb.dk> .4 The mouse-related event handlers for implementing drag-and-drop private bool isMouseDown = false.Understanding device support 95 your responsibility to free the mouse’s attention by calling the ReleaseMouseCapture method Snippet 4. private Point offs B C# C D This snippet shows the three steps necessary to implement the powerful drag-and-drop functi Licensed to SEB Link A/S .Henrik Thiesen <henrik.

5 The default look of a TextBox. By default.2. This value will change if a ENABLING MULTILINE TEXT SUPPORT The TextBox has built-in support for handling multiline text input. you can begin collecting items such as 4. i Snippet 4.dk> .96 CHAPTER 4 Handling user interaction 4. The TextBox in this case is defined within a Sta Result <StackPanel Orientation="Horizontal"> <TextBlock Text="Name: " /> <TextBox Text="Cha B This snippet shows a basic TextBox B with a preset Text value.1 Handling basic text The TextBox control enables your users to edit and view text. As basic as this may sound. this featur Licensed to SEB Link A/S .Henrik Thiesen <henrik.thiesen@seb.2 Delivering text controls Once you can respond to events from an input device.

dk> .Henrik Thiesen <henrik.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefin This snippet shows a multiline TextBox enabled through the AcceptsReturn and TextWrapping p MASTERING TEXT SELECTION The TextBox has built-in support for selecting portions of text within a TextBox.6 A multiline text box.Delivering text controls 97 Snippet 4.thiesen@seb. In line-of-business applications. A user ca XAML Licensed to SEB Link A/S . multiline text boxes ar Result <Grid> <Grid.

dk> .Henrik Thiesen <henrik. Notice the mask used in each field. <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" / XAML B C <TextBlock Text="Confirm: " FontFamily="Verdana" Grid. the SelectionStart property will return the index of the carat. This element is designed to Snippet 4.7 Result The syntax of the PasswordBox. The se 4.Row="1" /> <PasswordBox PasswordChar= 3 Programmatically changing the SelectionStart and SelectionLength properties only works when Licensed to SEB Link A/S .98 CHAPTER 4 Handling user interaction text isn’t selected.2.thiesen@seb.2 Collecting sensitive data Silverlight provides a special control called the PasswordBox.

thiesen@seb.6 The options available within the ClickMode enumeration Description Fires the Clic Option Hover Press Release Licensed to SEB Link A/S . Most of those options we Table 4.dk> .3 Button controls Section 4.Henrik Thiesen <henrik.2 showed the text controls available within Silverlight. This snippet also uses a cust 4.Button controls 99 This snippet shows the syntax used to create a PasswordBox B.

dk> .100 CHAPTER 4 Handling user interaction The ClickMode enumeration can be used to define a small part of the behavior of a button.Content> <StackPanel> <TextBlock Tex B This table begins to show the flexibility provided with a ContentControl.1 The Button The traditional Button is a simple ContentControl that a user can click to perform an actio Licensed to SEB Link A/S .thiesen@seb. X B B <Button Height="30" Width="90"> <Button. As you progress t 4.3.7 Button The flexibility of a ContentControl is displayed in these three buttons. T Table 4.Content> <TextBox HorizontalAlignment="Stretch" Hei <Button Padding="10" Height="120" Width="180"> <Button.Henrik Thiesen <henrik.

8 Result The general syntax for a Button XAML <Button x:Name="myButton" Content="Save" Height="30" Width="90" /> As you can see. the buttons in table 4. This control uses the NavigateUri pro Licensed to SEB Link A/S .dk> .7 are slightly more complex than the one shown in th 4. Thi Snippet 4.thiesen@seb.Button controls 101 makes the Button class special is the default appearance it creates around the Content.3.Henrik Thiesen <henrik.2 The HyperlinkButton The HyperlinkButton control is designed to create a button that looks and behaves like a hy Snippet 4.9 Result A HyperlinkButton in action Search in a New Window <HyperlinkButton x:Name="myHyperlinkButton" Content="Search in a New Window" NavigateUri="h XAML B C This snippet shows a basic HyperlinkButton in action.

the NavigateUri will load in a new window.3.8 CHAPTER 4 Handling user interaction The acceptable options for the TargetName property Target Value Description Launches the UR _blank. imagine having t RADIOBUTTON SELECTION A RadioButton is a kind of ToggleButton.dk> . A ToggleButton represents a button that can change Snippet 4. or _search _parent.3 The RadioButton A RadioButton represents a choice within a group of options.10 The default appearances of a checked and unchecked RadioButton Result <StackPanel> <TextBlock Text="What is your favorite flavor of ice cream?" /> <RadioB B Licensed to SEB Link A/S .102 Table 4. It’s important to remembe 4. For instance. _media. or _top whitespace characters.Henrik Thiesen <henrik.thiesen@seb. _self.

11 Manually controlling RadioButton groupings Result <StackPanel> <TextBlock Text="What is your favorite flavor of ice cream?" /> <RadioB B This snippet shows how the GroupName property can empower you throughout your development t Licensed to SEB Link A/S .Button controls 103 This snippet shows two options for a single question. In Snippet 4.thiesen@seb. You can see that the first option is RADIOBUTTON GROUPING A grouping of RadioButton items represents the choices available for a single situation.dk> .Henrik Thiesen <henrik.

dk> .12 A basic CheckBox setup Result <StackPanel> <TextBlock Text="Please select your favorite pizza toppings:" /> <Check Selecting multiple CheckBox elements at the same time is possible because the CheckBox isn’ Snippet 4. Unlike th Snippet 4.Henrik Thiesen <henrik.thiesen@seb. The fact that the CheckBo XAML XAML Licensed to SEB Link A/S .4 The CheckBox The CheckBox control enables a user to select whether or not an option is chosen.104 CHAPTER 4 Handling user interaction 4.3.13 shows the look and syntax of a three-state CheckBox.13 Using three-state mode check boxes Result <StackPanel> <CheckBox IsThreeState="True" IsChecked="False" Content="Unchecked" /> Snippet 4.

1 The ListBox The ListBox is probably the most basic items control.4.14 A ListBox that displays the days of the week Result <ListBox x:Name="myListBox"> <ListBox.3.Henrik Thiesen <henrik.Items> <ListBoxItem><TextBlock>Sunday.The ItemsControl 105 4. June 1< This snippet shows a very basic ListBox in action.dk> .4 The ItemsControl In section 4. This ListBox uses the Items property to XAML Licensed to SEB Link A/S . This control enables you to show mult Snippet 4. we discussed the controls derived from the ButtonBase class that represent 4.thiesen@seb.

Henrik Thiesen <henrik.thiesen@seb.106 CHAPTER 4 Handling user interaction Snippet 4.15 Using a ListBoxItem as a ContentControl Result <ListBox x:Name="myListBox"> <ListBox.Items> <ListBoxItem> <StackPanel Height="80" O Licensed to SEB Link A/S .dk> .

The ItemsControl 107 This snippet shows a ListBox control with much richer ListBoxItem elements than those shown 4. As you can see. Thes Snippet 4.14 merges the UI with the data used in the list.2 The ComboBox The ComboBox gives users the ability to select a single option from a list of choices. you’ll see how to XAML Licensed to SEB Link A/S .Items> <ComboBoxIte Snippet 4. this control delive 4 Snippet 4. In chapter 5.thiesen@seb.4.Henrik Thiesen <henrik.dk> .16 A ComboBox that has been used to select an item Result <ComboBox x:Name="myComboBox" Height="28" Width="180"> <ComboBox.16 shows the appearance of a closed ComboBox.

17 The basic syntax of a TabControl Result <UserControl x:Class="Snippet4_17. This ItemsControl is d Snippet 4.3 The TabControl The TabControl is another ItemsControl available within Silverlight. 4.Henrik Thiesen <henrik. but the XAML Licensed to SEB Link A/S .microsoft.dk> .4. every element in each tab is also constructed.thiesen@seb.Page" xmlns="http://schemas.108 CHAPTER 4 Handling user interaction The ComboBox also provides three members that make it unique from the other list controls.com/winfx/20 5 When the TabControl is constructed.

dk> . Because TabControl is Snippet 4.The ItemsControl <ext:TabItem> <StackPanel Orientation="Vertical"> <ListBox> <ListBoxItem Content="Beef" /> 109 This snippet shows an entire page.18 Customizing the Header of a TabItem Result <StackPanel x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left"> <Text XAML Licensed to SEB Link A/S .thiesen@seb. which includes a basic TabControl.Henrik Thiesen <henrik.

Header> <StackPanel Orientation="Vertical"> <ListBox> <ListBoxI This snippet shows a TabControl with two TabItem elements. If XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik. Each element has a Header.dk> .110 CHAPTER 4 Handling user interaction </StackPanel> </ext:TabItem. visual interface for selecting one or more dates.4. we discussed the available list controls.1 Calendar The Calendar control provides a rich. Note 4.thiesen@seb.5 Date controls In section 4. which mimic a lot of the function 4.5.

but there may be 6 Although the DisplayMode property can be set at startup.Date controls 111 Snippet 4. This Calendar defaults to a tra CONFIGURING THE DISPLAY By default.dk> .Henrik Thiesen <henrik.microsoft.thiesen@seb.Page" xmlns="http://schemas. the user can always change the Cal XAML Licensed to SEB Link A/S . the Calendar control provides a familiar way to select a date.com/winfx/20 This snippet shows the basic look and syntax of a Calendar.19 The default appearance and basic syntax of a Calendar Result <UserControl x:Class="Snippet4_19.

th Table 4.thiesen@seb. This value defaults to EMPOWERING DATE SELECTION The Calendar control enables you to restrict the dates that can be selected.112 Table 4.10 The options available within the CalendarSelectionMode enumeration Option Multip None SingleDate SingleRange This table shows the options that you can use as the SelectionMode of a Calendar.Henrik Thiesen <henrik. which happens to be a DayOfWeek value. By defaul Licensed to SEB Link A/S .dk> . By default.9 Option CHAPTER 4 Handling user interaction The CalendarMode options that can be used for the DisplayMode property Month Year Decade Sample the FirstDayOfWeek property.

Henrik Thiesen <henrik. If a user were to select the calen XAML Licensed to SEB Link A/S .com/winfx/20 This snippet shows the basics of the DatePicker control.Date controls 113 4.thiesen@seb.5.dk> .microsoft.2 DatePicker The DatePicker control empowers the user to choose a single date. Unlike the Calendar contr Snippet 4.20 The default appearance and basic syntax of a DatePicker Result <UserControl x:Class="Snippet4_20.Page" xmlns="http://schemas.

For insta Table 4.dk> .6 Choosing from a numeric range Imagine a scenario where you need to select or see a value between two endpoints.11 The options that can be used to format the SelectedDate. Because th Licensed to SEB Link A/S .Henrik Thiesen <henrik.114 CHAPTER 4 Handling user interaction Table 4.12 The properties associated with defining the range of a RangeBase instance Descri Property Value Minimum Maximum This table shows the properties that make up the bounds of a RangeBase instance. These options can be us Short 5/1/2008 4.thiesen@seb.

6. This can be useful for Snippet 4.6.Choosing from a numeric range 115 4.22 An indeterminate ProgressBar Result XAML This snippet creates a radically different effect than the ProgressBar shown in snippet 4.dk> .Henrik Thiesen <henrik.2 Implementing a Slider A Slider provides an intuitive way to enable a user to select from a range of values.1 Using the ProgressBar A ProgressBar can be used to show the overall progress of an action. This ProgressBar sets the Maximum value to 100. These XAML <StackPanel> <ProgressBar x:Name="myProgressBar" Height="30" IsIndeterminate="True" /> </St Licensed to SEB Link A/S . Not Snippet 4.thiesen@seb.2 4.21 A basic ProgressBar Result <StackPanel> <ProgressBar x:Name="myProgressBar" Height="30" Minimum="1" Maximum="10 This snippet shows a basic ProgressBar.

I 4.thiesen@seb. The thumb represents the current Value within the range of values.7.23 A basic Slider to choose between 1 and 10 Result This snippet shows a basic Slider that enables a user to select a value between 0 and 10. This c XAML <StackPanel> <Slider x:Name="mySlider" Minimum="0" Maximum="10" Value="5" /> </StackPanel> Licensed to SEB Link A/S .1 Popping up a dialog box Silverlight enables you to simulate a dialog box through a control called the Popup.dk> .Henrik Thiesen <henrik. M 4.7 Displaying visual prompts Let’s face it: There are certain times when you need to really grab the user’s attention. The t Snippet 4.116 CHAPTER 4 Handling user interaction “thumb” can slide.

Page" xmlns="http://schemas.24 A basic Popup Result <UserControl x:Class="AgePopup. This Popup element uses a Border as its Child.Henrik Thiesen <henrik. the Popup doesn’t derive from the Control class. UNDERSTANDING THE POPUP BEHAVIOR Unlike most controls.Displaying visual prompts 117 Snippet 4.dk> .microsoft. the Popup d Licensed to SEB Link A/S .com/winfx/2006/ B This snippet shows a basic Popup element B. Instead.thiesen@seb.

Henrik Thiesen <henrik.118 CHAPTER 4 Handling user interaction Popup.2 Prompting for a file The OpenFileDialog class empowers you to ask users for one or more files from their filesys LAUNCHING THE DIALOG BOX To give your users the opportunity to select a file. or multiple files.dk> .7. Instead.thiesen@seb. 4. you must instantiat Licensed to SEB Link A/S . This is also true when you are deciding on posi POSITIONING THE POPUP Positioning a Popup is slightly different than positioning other FrameworkElement objects. you must manually set them.

but y Snippet 4.Displaying visual prompts Table 4. you have flexibility in customizing the selection experience.13 Result OpenFileDialog openFileDialog = new OpenFileDialog().25 Creating an OpenFileDialog using the properties from table 4. openFileDialog.Henrik Thiesen <henrik.dk> .Filter = "Text B C This snippet shows a basic OpenFileDialog box that enables a user to select a text or XML f Licensed to SEB Link A/S .13 The configuration properties available on the OpenFileDialog Description This st 119 Property Filter FilterIndex Multiselect As this table displays.thiesen@seb.

120 RETRIEVING THE RESULTS CHAPTER 4 Handling user interaction Once a user exits an OpenFileDialog.26 Retrieving the selection of an OpenFileDialog bool? fileWasSelected = openFileDialog. the ShowDialog method will return a nullable bool valu Snippet 4. File. StreamReader reader = fileInfo. if (fileWasSelected == true) { FileInf From this snippet.dk> . you can see that once a user opens the dialog box.27 Retrieving the selection of an OpenFileDialog. working with a text file in Silverlight is incredibly trivial. myText As this snippet shows.OpenText(). It’s C# Licensed to SEB Link A/S . The contents of a selected file FileInfo fileInfo = openFileDialog.Henrik Thiesen <henrik.thiesen@seb.ShowDialog(). you can get the selec READING THE RESULTS The FileInfo class provides a special bridge from the local filesystem to the security sand Snippet 4.

8 Miscellaneous controls This chapter has covered fifteen of the controls available in Silverlight 2.Henrik Thiesen <henrik.8.Miscellaneous controls 121 ask a user for a file.thiesen@seb. These t 4.2 Collecting drawings Silverlight provides an intuitive way to collect handwritten information through an element Licensed to SEB Link A/S . This content can be any 4.dk> . This rich cont 4.8. The Popup element provides another way to prompt your users.1 Creating a border The Border element is designed to provide trimming around content.

Windows public void ipMouseLeftButtonDown(object sender.com/winfx/2006/x This snippet creates a basic InkPresenter within a Canvas. This object can be thoug Snippet 4.C XAML B C D Licensed to SEB Link A/S .dk> . If you were to create a Silverli COLLECTING INK Collecting ink within Silverlight is similar to the drag-and-drop process discussed in sect Snippet 4.Henrik Thiesen <henrik. MouseButtonEventArgs e) { myInkPresenter.thiesen@seb. you must define an InkPresenter object.28 A basic InkPresenter <UserControl x:Class="InkPresenter01.Page" xmlns="http://schemas.microsoft.29 Beginning to construct the Stroke.122 CHAPTER 4 CREATING THE INK CANVAS Handling user interaction To create an ink’s canvas. This class is defined in the System.

31 Finishing the Stroke public void ipMouseLeftButtonUp(object sender.dk> .29. MouseButtonEventArgs e) { myInkPresenter. MouseEventArgs e) { if (this.Rel This snippet completes the process of drawing a Stroke on an InkPresenter. By setting the S STYLING THE INK The Stroke element provides a property called DrawingAttributes that empowers you to alter C# Licensed to SEB Link A/S . This r Snippet 4.Henrik Thiesen <henrik.stroke != null) { this.thiesen@seb. C# B This snippet adds to the Stroke B initialized in snippet 4.Miscellaneous controls 123 The member variable stroke is reset each time the user depresses the input device B. You’ll notice that this task Snippet 4.30 Adding to the Stroke through the MoveMove event public void ipMouseMove(object sender.

124 CHAPTER 4 Handling user interaction namespace.9 Summary This chapter showed a variety of the rich and extensive controls found in Silverlight 2. Th Licensed to SEB Link A/S .dk> .thiesen@seb.32 Stylizing a Stroke <InkPresenter x:Name="myInkPresenter" Background="Silver" Height="300" Width="300"> <InkPre B XAML C D As this snippet shows.Henrik Thiesen <henrik. you can define the DrawingAttributes of a Stroke within XAML C. Snippet 4. This 4. It provides four properties that allow you to specify a Stroke element’s Color.

A Licensed to SEB Link A/S .Henrik Thiesen <henrik. such as the DataGrid in chapter 5 and the MultiScaleImage in chapter 7.thiesen@seb.Summary 125 be covered later.dk> .

Getting down with data binding This chapter covers ■ ■ ■ Mastering binding with a data source Learning about the DataGrid Exploring LINQ in Silverli Throughout chapter 4 you saw the garden of input controls that empower you to harvest data 126 Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik.thiesen@seb.

1. Figure 5. This illustration uses the situation of binding the current time of day to a TextBox to giv 5.1 A conceptual view of data binding. This chapter will end with an overview of the distinguishing data querying enhanc 5.thiesen@seb. The f BINDING AT RUNTIME Binding to a data source at runtime is a common approach used in event-driven application d Licensed to SEB Link A/S .Binding with your data 127 DataGrid.dk> .1 Mastering the binding syntax Silverlight gives you the ability to create a Binding using two different approaches.Henrik Thiesen <henrik.1 Binding with your data Data binding is a powerful way to create a connection between your UI and a source of data.

thiesen@seb. binding.Henrik Thiesen <henrik. This Snippet 5.Mode = Bi This snippet shows how to bind the value of a CLR property to a UI element at runtime. binding.Now. This snippet shows how easy it is to remove a binding after it has been set. Text = "Binding Removed".128 CHAPTER 5 Getting down with data binding Snippet 5. B C D Binding binding = new Binding("TimeOfDay").Source = currentTime.dk> .2 C# C# Removing a Binding from a TextBox myTextBox.1 XAML Adding a Binding to a TextBox from C# <TextBox x:Name="myTextBox" /> DateTime currentTime = DateTime.Text = "Binding Removed". This feature i BINDING AT DESIGN TIME Binding to a data source at design time is a common feature in declarative markup languages Licensed to SEB Link A/S .

This binding is associated with 5.Binding with your data 129 approach if you’ve used ASP.NET or WPF.Henrik Thiesen <henrik. In essence. don’t worry.dk> . If you haven’t.1.Now.DataContext = currentTime. this appro Snippet 5.thiesen@seb. Mode=OneWay}" /> B DateTime currentTime = DateTime.3 XAML Binding a property to a TextBox in XAML <TextBox x:Name="myTextBox" Text="{Binding TimeOfDay.2 Choosing a binding mode The Binding class gives you the ability to determine how data can flow between the source a ONETIME The OneTime option sets the target property to the source property when a binding is initia Licensed to SEB Link A/S . myTextBox. C# C This snippet shows how to create a binding at design time.

2 A conceptual view of OneTime binding to a data source be automatically sent to the target. If the target changes. Think of the speedomete TWOWAY TwoWay binding enables two properties that are bound to change each other.thiesen@seb. the target will be set only when the source i ONEWAY The OneWay BindingMode is the default option used when you create a Binding. This may sound r source changes. Instead. This option gi Figure 5. This process can be seen in f Licensed to SEB Link A/S . the source is updated.Henrik Thiesen <henrik.dk> .130 CHAPTER 5 Getting down with data binding Figure 5.3 A conceptual view of OneWay binding to a data source This figure shows how the OneWay BindingMode works at a high level.

2 Understanding your data source In section 5. as well as edit.1.1 Binding to a property Silverlight gives you the flexibility to bind to any CLR property you want. we skimmed over the general concept of data binding.Henrik Thiesen <henrik.dk> .4 A conceptual view of TwoWay binding to a data source add. We discussed this conc 5. You saw this wi Licensed to SEB Link A/S .Understanding your data source 131 Figure 5. This process of editing preexisting data practically begs for T 5. data.2.thiesen@seb.

For instance.dk> .Henrik Thiesen <henrik.132 CHAPTER 5 Getting down with data binding A change-notification handler notifies a binding target that a change has been made. :) is the sign Licensed to SEB Link A/S .4 Implementing the INotifyPropertyChanged interface public class Emoticon : INotifyPropertyChanged { public event PropertyChangedEventHandler P B C C# public void UpdateProperty(string propertyName) { if (PropertyChanged != null) { PropertyCh D This snippet shows how to implement the System.thiesen@seb.ComponentModel namespace’s INotifyPropertyCh 1 An emoticon is a symbol that represents a feeling or emotion. This e Snippet 5.

com/winfx/2006/xaml/p B XAML C <TextBlock Text="Name:" /> Licensed to SEB Link A/S .5 Binding an Emoticon object (defined in snippet 5.Understanding your data source 133 in property values.Henrik Thiesen <henrik. The interface can be used to ensure that your UI component and desired 5.Page” xmlns="http://schemas. we’ve primarily focused on binding individual properties to UI components Snippet 5.2 Binding to an object Up to this point.4) to a Grid <UserControl x:Class=”Chapter05.2.dk> .thiesen@seb.microsoft.

2.Henrik Thiesen <henrik.4) to a ListBox throug Result Licensed to SEB Link A/S . There are numerous t Snippet 5. The Te 5.dk> .6 Binding a collection of Emoticon objects (from snippet 5. Mode=TwoWay} D C# E This snippet shows how an object can be bound to elements within a FrameworkElement.3 Binding to a collection Binding to a collection is an important task in a lot of applications.Column="1" /> XAML <TextBox Text="{Binding Name.thiesen@seb.134 CHAPTER 5 Getting down with data binding <TextBlock Text="Image:" Grid.

C# // Assume GetEmoticons() exists B This snippet shows how to bind a collection of objects to an ItemsControl.thiesen@seb.ItemsSource = emoticons. This snippet shows the impact of the DisplayMemberPath property on binding items B. myListBox. in this case a L Snippet 5.Understanding your data source 135 XAML <ListBox x:Name="myListBox" Height="100 /"></ListBox> List<Emoticon> emoticons = GetEmoticons(). As you C# // Assume GetEmoticons() exists Licensed to SEB Link A/S .dk> .ItemsSource = emoticons. myListBox.7 Result Using the DisplayMemberPath to improve the display of a list of items XAML <ListBox x:Name="myListBox" DisplayMemberPath="Name" Height="100" /> B List<Emoticon> emoticons = GetEmoticons().Henrik Thiesen <henrik.

2.Henrik Thiesen <henrik. This approach allows you to eas 5.3.1 Converting values during binding Silverlight allows you to dynamically convert values during data binding. data binding is a powerful way to show data. Occasionall 5. You can accomplis CREATING A VALUE CONVERTER To create a value converter.dk> .136 CHAPTER 5 Getting down with data binding snippet also shows the elegance of data binding in general.thiesen@seb. you must create a class that implements the IValueConverter in Licensed to SEB Link A/S .3 Customizing the display As you saw throughout section 5.

Globaliza C This snippet shows a value converter that converts a bool to Yes or No.Customizing the display 137 Snippet 5.8 A sample value converter. This p Licensed to SEB Link A/S . This converter uses USING A VALUE CONVERTER Using a value converter involves setting the Converter property of a Binding object. Type targetType.Henrik Thiesen <henrik. Ty B C# public object ConvertBack(object value. object parameter. This converter changes a bool to Yes or No and back a public class YesNoValueConverter : IValueConverter { public object Convert(object value.dk> .thiesen@seb. System.

This converter alters the Licensed to SEB Link A/S .dk> .thiesen@seb.Henrik Thiesen <henrik.8 to XAML XAML XAML <UserControl x:Class="Snippet5_9. The my pref Snippet 5. Converter={StaticResource myConve This snippet shows a basic Binding that uses a custom converter.microsoft.10 Using an IValueConverter in a Binding <TextBlock x:Name="myTextBlock" Text="{Binding IsCorrect.138 CHAPTER 5 Getting down with data binding Snippet 5.Page" xmlns="http://schemas.com/winfx/2006/xaml/ This snippet shows how to introduce a custom IValueConverter to the XAML world.9 Exposing the YesNoValueConverter from snippet 5.

dk> .11 A DataTemplate used with a ContentControl (a Button.Henrik Thiesen <henrik.2 Creating data templates A data template is a way to define how Table 5.Customizing the display 139 so you may consider using a value converter to scrub the HTML tags from a string before bin 5. to be precise).3.1 One example of a data template a piece of USING A DATATEMPLATE WITH A CONTENTCONTROL A ContentControl is a type of control defined by a single piece of content.thiesen@seb. Result <Button x:Name="myButton" Height="70" Width="210"> <Button. which we discus Snippet 5.ContentTemplate> <DataTem Licensed to SEB Link A/S .

This DataTemplate is applied t ■ C# XAML ■ When assigning your data source to the DataContext property. You may be wondering. Why sho RENDERING AN ITEMSCONTROL WITH A DATATEMPLATE The ItemsControl element is designed to display a collection of items.140 CHAPTER 5 Getting down with data binding <Image Source="{Binding Icon}" Height="40" Margin="10" /> <TextBlock Text="{Binding Name}" This snippet shows a basic DataTemplate applied to a Button.dk> .thiesen@seb.Henrik Thiesen <henrik. use the binding syntax within These two points make it seem like you’re running in circles. which are bound to a Licensed to SEB Link A/S .

Henrik Thiesen <henrik.Windows.thiesen@seb.dk> .4 The DataGrid The DataGrid is a list-style control that belongs to the System.Controls namespace.The DataGrid Snippet 5. you’ve seen how to fully customize the look of your data with data 5. to be precise 141 Result <ListBox x:Name="myListBox" Height="200"> <ListBox.12 An ItemTemplate used in an ItemsControl (a ListBox.ItemTemplate> <DataTemplate> <Sta Throughout this chapter. C# XAML Licensed to SEB Link A/S .

microsoft.com/winfx/2006 XAML B C List<Emoticon> emoticons = GetEmoticons().13 A basic DataGrid.dk> .thiesen@seb.4. myDataGrid. The easiest way to display data fro Snippet 5.Page" xmlns="http://schemas.ItemsSource = emoticons. Assume that the ItemsSource property is set in the code behi Result <UserControl x:Class="Chapter05.Windows. Throughout this sect 5.142 CHAPTER 5 Getting down with data binding involves choosing a prefix in order to use the control at design time.1 Displaying your data The DataGrid was designed to make displaying data easy.Data assembly to deliver the Data C# Licensed to SEB Link A/S .Controls.Henrik Thiesen <henrik. Voila! This snippet relies on the System.

Henrik Thiesen <henrik.thiesen@seb.2 The types of columns that can be automatically generated within a DataGrid Type D DataGridCheckBoxColumn This table shows the kinds of columns that can be automatically generated within a DataGrid Licensed to SEB Link A/S .The DataGrid 143 The DataGrid isn’t an ItemsControl The DataGrid takes advantage of a feature known as UI virtualization.dk> . UI virtualization mea EXPLORING BOUND COLUMNS When the AutoGenerateColumns property is set to true. the columns in a DataGrid are automat Table 5.

thiesen@seb.Henrik Thiesen <henrik.144 CHAPTER 5 Getting down with data binding MANUALLY WORKING WITH COLUMNS The DataGrid can use any column that derives from DataGridColumn.14 Manually adding columns to a DataGrid Result <Data:DataGrid x:Name="myDataGrid" AutoGenerateColumns="False"> <Data:DataGrid. These columns can be adde Snippet 5.dk> . In these s XAML Licensed to SEB Link A/S .Colum B This snippet shows how to add columns manually to a DataGrid at design time. These columns CUSTOMIZING THE ROWS A row within a DataGrid will most likely represent a summarized view of an item.

This property uses a DataT Licensed to SEB Link A/S . This DataTemplate shows the keyboard shortcut fo Result <Data:DataGrid x:Name="myDataGrid" AutoGenerateColumns="False" RowDetailsVisibilityM B XAML C This snippet shows how to use the RowDetailsTemplate property C.15 Using the RowDetailsTemplate.Henrik Thiesen <henrik.dk> . imagine adding a string property called “Keys” to the Emoticon class define Snippet 5.The DataGrid 145 how this works.thiesen@seb.

146 Table 5.thiesen@seb. including the headers. Th Table 5. The con VisibleWhenSelected This option will show the content in the RowDetailsTemplate for each selected row.4 Option All The options available through the DataGridHeadersVisibility enumeratio Licensed to SEB Link A/S .dk> . CUSTOMIZING THE HEADERS The DataGrid gives you the ability to customize every part of it.Henrik Thiesen <henrik.3 CHAPTER 5 Getting down with data binding The options available within the DataGridRowDetailsVisibilityMode enumeration Option Exampl Collapsed Visible This option forces the content in the RowDetailsTemplate to be shown for every row.

Users will be ab Licensed to SEB Link A/S .2 Editing grid data In addition to presenting data. T 5. Row This option displays only the row header. the DataGrid has the ability to edit data.dk> .4.4 Option Column 147 The options available through the DataGridHeadersVisibility enumeration (continued) Example None This option displays neither the row nor column headers.Henrik Thiesen <henrik.thiesen@seb.The DataGrid Table 5. This table shows the options available through the DataGridHeadersVisibility enumeration.

Henrik Thiesen <henrik.dk> . These events are triggered by the DataGrid and are 5.3 Sorting items The DataGrid has built-in support for sorting collections that implement the IList interfac Snippet 5.4.16 Empowering your users to sort the columns of a DataGrid Result <Data:DataGrid x:Name="myDataGrid" AutoGenerateColumns="False"> <Data:DataGrid.thiesen@seb.148 CHAPTER 5 Getting down with data binding the editing process through two events.Colum XAML B C Licensed to SEB Link A/S .

but 5.thiesen@seb.5.5 Language Integrated Query (LINQ) Throughout this chapter.1 Introducing LINQ LINQ enables you to query disparate data types within your C# or Visual Basic code.Language Integrated Query (LINQ) <Image Source="{Binding Icon}" /> </DataTemplate> </Data:DataGridTemplateColumn. consistent querying syntax. you’ve seen how to bind to data and how to display that data.dk> . This language enhancement provides a single. regardless of the XAML Licensed to SEB Link A/S .CellTemplat 149 This snippet shows two DataGridColumn instances enabling the user to sort the underlying It 5.Henrik Thiesen <henrik.

Henrik Thiesen <henrik. here’s a condensed list of some of the most o Table 5.thiesen@seb. Count( Type Aggregate Convert Group Join Order Projection Restrict Set Singleton Licensed to SEB Link A/S .5 LINQ enables you to seamlessly integrate disparate data types through managed co the IntelliSense feature built into the text.150 CHAPTER 5 Getting down with data binding Figure 5.5 A condensed list of operations available through LINQ Operation Average().dk> .

thiesen@seb. Then.Henrik Thiesen <henrik. so we can illustrat Licensed to SEB Link A/S .17 A basic LINQ query over an array of strings Result XAML <Grid x:Name="LayoutRoot" Background="White"> <ListBox x:Name="myListBox" Heigh B C# C // List the band names foreach (string musicalGroup in filtered) { ListBoxItem myListBoxIte This snippet initially creates an array of musical group names B.dk> .Language Integrated Query (LINQ) 151 Snippet 5.

dk> . What may come as a surpr Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik.152 CHAPTER 5 Getting down with data binding Snippet 5.18 Deferred querying in action Result XAML C# <Grid x:Name="LayoutRoot" Background="White"> <ListBox x:Name="myListBox" He B C In this snippet. the first foreach loop displays two band names B.

Language Integrated Query (LINQ) 153 5.5.2 LINQ to Objects LINQ to Objects empowers you to create queTable 5.6 A collection of fictional

ries over collections of objects directly within MusicalGroup objects your managed code. Fo Snippet 5.19 A traditional sample that retrieves all the bands within the Rock genre ordere // Retrieve all of the musical artists from the data source List<MusicalGroup> musicalGroup Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

154 CHAPTER 5 Getting down with data binding

This example shows a basic query whose results are then filtered down into a smaller subset Snippet 5.20 A LINQ statement that retrieves all the bands in the Rock genre ordered by the // Retrieve all of the musical groups from the data source List<MusicalGroup> musicalGroups

As you can see, the code in this snippet is significantly more compact than that in snippet 5.5.3

LINQ to XML LINQ to XML, or XLinq, gives you the ability to easily create and query XML data without ha <?xml version="1.0" encoding="utf-8" ?> <Albums> <Album ArtistID="1"> <Name>Trumpets and Tu XML Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Language Integrated Query (LINQ) <Album ArtistID="9"> <Name>The Chalkboard</Name> <ReleaseDate>08/27/2007</ReleaseDate> </Al 155

Although XPath and XQuery are widely used, these techniques are often inefficient because i Snippet 5.22 A query statement that retrieves all the albums by the artist with ID of 7 // Load all of the Albums from a data source XmlReader reader = XmlReader.Create("Albums.xm C# XML Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

156 { CHAPTER 5 Getting down with data binding C# if (reader.Name == "Album") { albumsByArtist.Add(album); break; } } } } } } }

This monstrous block of code performs a basic query using the efficient XmlReader object. U Snippet 5.23 A LINQ to XML example that retrieves all the albums by a specific artist from // Load all of the orders from a data source XElement element = XElement.Load("Albums.xml")

You may have noticed the XElement object within this snippet. The XElement class is part of 5.5.4

LINQ-ing it together After looking at LINQ to Objects and LINQ to XML it becomes apparent that this consistent q C# Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Language Integrated Query (LINQ) 157

Let’s imagine that you’re asked to find all the rock artist albums. From the example given Snippet 5.24 An example that shows using LINQ to join to two different types of data (in-me Result <UserControl x:Class="Snippet5_24.Page" xmlns="http://schemas.microsoft.com/winfx/20 Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

158 CHAPTER 5 Getting down with data binding rockGroup.Name, Convert.ToDateTime(album.Element("ReleaseDate").Value) select new Result { B C# myDataGrid.ItemsSource = rockAlbums;

This snippet shows that you are able to join two different types of data through LINQ. In a 5.6

Summary Throughout this chapter, you’ve seen the power of the Binding object. This object gives you Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Networking and communications This chapter covers ■ ■ ■ ■ Consumng web services Performing duplex communication Taking a REST Working with JSON data

Chapter 5 introduced you to the convenient data-binding mechanisms available within Silverl 159 Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

160 CHAPTER 6 Networking and communications Silverlight provides us with numerous methods to get to data hosted on other systems, from 6.1 Trust, security, and browser limitations You must consider several basic concepts when using the communication APIs in Silverlight. 6.1.1

It’s all a matter of trust The concept of trust applies to cross-domain access. If your application is hosted at http: Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Trust. and browser limitations 161 and the call will return as expected.xml Required Yes Yes Yes De XML Element/ Attribute access-policy cross-domain-policy policy allow-from Yes http-request-headers No domain Yes uri Yes grant-to Yes Licensed to SEB Link A/S . So.thiesen@seb.dk> . what does a properly formatted policy file look l Snippet 6.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allo This snippet shows the minimum needed in a clientaccesspolicy.Henrik Thiesen <henrik.1 Base clientaccesspolicy. security.xml to allow HTTP access to a Table 6.xml for WebClient or HTTP access <?xml version="1.1 Elements and attributes allowed in clientaccesspolicy.

dk> .2 More restrictive client access policy <?xml version="1.Henrik Thiesen <henrik.1 CHAPTER 6 Networking and communications Elements and attributes allowed in clientaccesspolicy.xml (continued) Required Yes Descript Element/ Attribute resource Path Yes include-subpaths No socket-resource Yes Port Yes Protocol Yes Now we know that you’re anxious to see how to connect to data from within your application.thiesen@seb.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allo XML Licensed to SEB Link A/S . Snippet 6.162 Table 6.

xml 6. security.1. you can take other steps DATA INTEGRITY Never trust that your data source is going to return pure.2 Making your application secure Just as you put a valid policy file in place for security reasons.4 If the domain hosting the web service you’re calling has either the clientaccesspolicy. you should use Hypertext Transfer Protocol over Secu COOKIES Because Silverlight uses the browser’s networking stack. Modifica ■ XML ■ It may only be used for WebClient (WebClient usage is discussed in chapter 11. and browser limitations </allow-from> <grant-to> <resource path="/api"/> </grant-to> </policy> </cross-domain-acces 163 The elements and attributes shown apply for connecting to any HTTP-based resource.thiesen@seb. clean data every time.Trust. cookies for the current domain als Licensed to SEB Link A/S . section 11.dk> . It’s poss HTTPS Anytime you’re passing sensitive data.Henrik Thiesen <henrik.

164 CHAPTER 6 Networking and communications you’re hosting your Silverlight in an authenticated application that uses tokens stored in 6.Henrik Thiesen <henrik. http:/ /www.com and ASYNCHRONOUS ONLY All communication from within the Silverlight application is done asynchronously because of Licensed to SEB Link A/S .thiesen@seb.3 Limitations of the browser A few limitations apply to Silverlight due to its use of the networking API of the host bro CONNECTION COUNT LIMIT The number of connections to a single subdomain (for example.1.dk> .microsoft.

thiesen@seb.dk> . you’re thinking about Simple Object Access Protoco SERVICE REFERENCES The easiest way to connect to a service is through a Service Reference proxy. a fact that can cause tr 6.2 Connecting to data sources Nearly every application built today. needs data to accomplish its 6.Connecting to data sources 165 Note that the asynchronous behavior can occur on multiple threads. If the web se 1 2 In Visual Studio 2008.1 Using SOAP services When you think of a classic web service. even using Silverlight. right-click your Silverlight project and choose Add Service Referenc Licensed to SEB Link A/S .2.Henrik Thiesen <henrik.

3 Result Calling a simple SOAP service <TextBlock x:Name="txResults" Grid.dk> .RowSpan="2" Grid.166 CHAPTER 6 Networking and communications 3 can then enter a Namespace that you want to refer to the service by into the textbox and th When the service reference is created. You need to add tw Snippet 6.Column="0" Height="Auto" W XAML B C# C Licensed to SEB Link A/S . Visual Studio also adds references to the System.Run RECEIVING DATA WITH THE PROXY Connecting to and downloading data from a simple SOAP service is simple.Henrik Thiesen <henrik.thiesen@seb.Row="0" Grid.

GetTimeCom 167 D E This snippet shows the entire process of creating the proxy.Connecting to data sources proxy.dk> .thiesen@seb. SilverService. adding an event handler. calli Licensed to SEB Link A/S . } void proxy_GetTimeCompleted(object sender.Henrik Thiesen <henrik.GetTimeAsync().

SilverService. Anoth Licensed to SEB Link A/S .168 CHAPTER 6 SENDING DATA USING THE PROXY Networking and communications If you’re thinking that all you need to do to send data to a SOAP service using a service r Snippet 6.4 Result Sending data to SOAP service <TextBlock x:Name="txResults" Grid.thiesen@seb.GetCoolTextCompletedEventArg This snippet shows the sending of a single int as a parameter to the GetCoolText method on USING COMPLEX DATA TYPES Sending and receiving complex data types over a SOAP service is also a simple matter.GetCoolTextCompletedEventArgs> B } void proxy_GetCoolTextCompleted(object sender.Row="0" Grid.dk> .GetCoolTextCompleted += new EventHandler<SilverService.RowSpan="2" Grid.Column="0" Height="Auto" W C# XAML proxy.Henrik Thiesen <henrik.

Connecting to data sources 169 Snippet 6.ComponentModel.5 Using complex data types with SOAP service [WebMethod] public void SetSomething(int count.AsyncCompletedEventAr E } void proxy_SetSomethingCompleted(object sender.ComponentModel. WsUser myObject) { //Perform database opera B Service C private void UploadUser() { Binding myBinding = new BasicHttpBinding(). System.thiesen@seb.Henrik Thiesen <henrik. EndpointAddress myE D C# proxy.dk> .AsyncCompletedEvent This snippet shows how you can use complex data types on SOAP services from within your Sil Licensed to SEB Link A/S .SetSomethingCompleted += new EventHandler<System.

means several things. RoutedEventArgs e) { UIThread = Synchronizat Licensed to SEB Link A/S . or REST.170 CHAPTER 6 Networking and communications 6.2.6 Threading the UI private SynchronizationContext UIThread.Henrik Thiesen <henrik.dk> .thiesen@seb. in this case.2 Time for a REST Representational State Transfer. it refers to BYPASSING THREADING PROBLEMS The asynchronous nature of Silverlight web service calls can create threading problems for Snippet 6. C# B C private void btnSingleXml_Click(object sender.

BeginGetResponse(SingleXmlCallBack. request).7 Getting data from a REST service private void btnSingleXml_Click(object sender.thiesen@seb.dk> . RoutedEventArgs e) { UIThread = Synchronizat B Licensed to SEB Link A/S . } private void SingleXmlCallBack(IAsy 171 C# D E The first thing you do in this snippet is create a class variable of type SynchronizationCo GETTING FROM REST SERVICES In relation to Silverlight. although REST may dictate the method in which a resource is acc Snippet 6.Henrik Thiesen <henrik.Connecting to data sources request.

Henrik Thiesen <henrik. Create an The BeginGetResponse method initiates the call to the service and registers the passed-in m POSTING TO REST SERVICES Most RESTful services use GET to retrieve data and POST to send it. There are three n 1 2 3 C# C Create a Uri object and initialize it with the path and. Because the default HTT Snippet 6. optionally.dk> . the UriKind. you’re making a simple request to a RESTful web service.8 POSTing data to a REST service private void btnTest_Click(object sender. RoutedEventArgs e) { UIThread = SynchronizationCo C# B Licensed to SEB Link A/S .172 } CHAPTER 6 Networking and communications private void SingleXmlCallBack(IAsyncResult result) { HttpWebRequest request = (HttpWebRequ In this snippet.thiesen@seb.

StreamWriter dataWriter = new 173 Because REST services don’t have methods.3 Making the data usable We’ve now discussed ways to request data from both SOAP and REST services. you need to add any data to be sent to the servic 6.Making the data usable HttpWebRequest request = (HttpWebRequest) result.dk> .1 Reading POX Plain Old Xml (POX) has been the data format of choice on the internet for nearly a decade.3.AsyncState. What we haven’t 6. Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik.

RowDefinitions> <RowDefiniti Licensed to SEB Link A/S .9 Getting the XML Result <Grid x:Name="LayoutRoot" Background="#FF959595"> <Grid. Due to its long life and universal acceptance.dk> .174 CHAPTER 6 Networking and communications virtually guaranteed its acceptance. the Sil SETTING UP For each example that follows.thiesen@seb. we’re using the same Silverlight application and the same we Snippet 6.Henrik Thiesen <henrik.

txCity.10 shows the LINQ to XML version of UpdateUiText.Text Snippet 6.9. txName.thiesen@seb.ToString(). It shows how using LINQ to acce Licensed to SEB Link A/S .Text = root.Making the data usable XAML FontFamily="Courier New" FontSize="11"/> </StackPanel> </Grid> private void LoadXML(ob 175 In snippet 6.Text = (string)root.Element("city"). We discussed LINQ to XML public void UpdateUiText(object stream) { XmlReader responseReader = XmlReader.dk> .Create((Stre B C# C txtResults. you’re using the HttpWebRequest object to retrieve the response stream from XLINQ XLINQ is the newest way of parsing usable data from an XML stream.Henrik Thiesen <henrik.

name.12 Using XmlSerializer public void UpdateUiText(Object stream) { XmlReader responseReader = XmlReader.176 XMLREADER CHAPTER 6 Networking and communications It’s entirely possible to use the XmlReader itself. without using a higher-level object to Snippet 6. public class Neighbourhood { public Licensed to SEB Link A/S . txName.Create((Stre B C C# D txCity.city.thiesen@seb.Text = hood..Text = hood. } .Henrik Thiesen <henrik.11 Using XmlReader public void UpdateUiText(object stream) { XmlReader responseReader = XmlReader. This Snippet 6..Create((Stre Snippet 6.11 uses the plain XmlReader to step through the returned XML to find the values y XMLSERIALIZER The XmlSerializer provides a way to convert an XmlReader into strongly typed objects.dk> .

13 Sample JSON Result { "neighbourhood": { "adminName2": "New York County". } adminNam 177 You can see that using an XmlSerializer allows you to create a strongly typed object from t 6. "adminCod C# Licensed to SEB Link A/S .dk> . JSON prov Snippet 6.Henrik Thiesen <henrik. "adminCode2": "061".Making the data usable public public public public } string string string string adminCode2 { get. it’s possible that you’re already familiar with JSON.thiesen@seb. set.3.2 Converting JSON If you’ve worked with AJAX.

Load((St One way to read JSON data is by using JsonObject. there’s more than one way to use JSON-formatted data returned from a web servi Snippet 6.thiesen@seb.178 CHAPTER 6 Networking and communications JSON "name": "Central Park".15 Reading JSON with the DataContractJsonSerializer public class MyResults { public Neighbourhood neighbourhood { get. set.Henrik Thiesen <henrik.Load to convert the stream into an object DATACONTRACTJSONSERIALIZER Another way to access returned JSON involves using the DataContractJsonSerializer to deseri Snippet 6. "adminName1 This snippet represents a simple but typical JSON object. "countryCode": "US". } } C# C# Licensed to SEB Link A/S .dk> .14 Reading JSON with the JsonObject public void UpdateUiText(Object stream) { JsonObject hood = (JsonObject)JsonObject. the returned JSON JSONOBJECT As with XML. "city": "New York City-Manhattan". As you can see.

3. This information can b READING SYNDICATED FEEDS Reading syndicated content is an incredibly easy process.Making the data usable . This process is simple because bo Snippet 6.. RoutedEventArgs e) { uiThread = SynchronizationCon C# Licensed to SEB Link A/S .16 Downloading and displaying an RSS feed private void btnRSS_Click(object sender.3 Reading syndicated feeds Atom and RSS are XML formats that make it easy to share information.thiesen@seb.Henrik Thiesen <henrik.. as well as the me 6.dk> . public void UpdateUiText(Object stream) { DataContractJsonSerializer ser = new DataCont 179 This snippet shows the classes that hold the data once it’s deserialized.

Each property is sh Categories C# Category Category Contributors contributor a10:contributor Copyright Rights Copyright Description Subtitle Description Licensed to SEB Link A/S .dk> .com/ToCodeOrNotToCode").16 shows how to load an Atom 1. HttpWebRequest request The code in snippet 6.2 The main feed properties available through a SyndicationFeed.Henrik Thiesen <henrik.180 CHAPTER 6 Networking and communications Uri uri = new Uri("http://feeds.0 or RSS 2.thiesen@seb.0 feed over the http:// pro Table 6.feedburner.

0 author RSS 2.3 The properties available for a SyndicationItem Atom 1.2 The main feed properties available through a SyndicationFeed.thiesen@seb. Each property is sh Id id a10:id ImageUrl Logo Image Language Lang language LastUpdatedTime Links updated link lastBuildDate a10:link Title title Title This table shows the vast amount of information available through each feed.Henrik Thiesen <henrik. This informati UNDERSTANDING THE FEED ITEMS The Items property of a SyndicationFeed object represents the collection of items in a feed Table 6.dk> .Making the data usable 181 Table 6.0 managingEd Property Authors Categories category category Licensed to SEB Link A/S .

0 content contributor RSS Property Content Contributors Copyright Id LastUpdatedTime rights id updated Copyright a10:id a10:updated Links link Link PublishDate published pubDate SourceFeed source Source Summary Title summary title Description Title That’s enough talk about the properties and what they do. now let’s put some of them to use USING SYNDICATEDFEED WITH RSS The RSS format allows content publishers to syndicate pure information.3 CHAPTER 6 Networking and communications The properties available for a SyndicationItem (continued) Atom 1.182 Table 6.17 An example RSS feed based on some blog <?xml version="1. based on the fact t Snippet 6.0" encoding="utf-8" ?> <rss version="2.dk> .0"> <channel> <title>Chad Campbell XML Licensed to SEB Link A/S .Henrik Thiesen <henrik.thiesen@seb.

but it does illustrate the b Snippet 6.com/myFirstBlogPost.thiesen@seb.dk> .Making the data usable <item> <title>My First Blog Post!</title> <link>http://somedomain.18 Displaying Syndicated content Result <Button Height="21" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="68" You can see how easy it is to display RSS content in your Silverlight application. but ther C# XAML XML Licensed to SEB Link A/S .html< 183 The content in this snippet doesn’t come from a real RSS feed.Henrik Thiesen <henrik.

w3.org/2005/Atom"> <title>Ch Because the Content of the entry is formatted as XML and is valid XAML.dk> .Henrik Thiesen <henrik.thiesen@seb.19 An example Atom feed based on some blog <?xml version="1. This format gives content provi Snippet 6.184 CHAPTER 6 Networking and communications HTML content in the RSS feed. Silverlight ca READING ATOM Atom is a newer entry into the world of online syndication.0" encoding="utf-8"?> <feed xmlns="http://www. Although this looks nice in a feed aggregator. it’s possible to cr XML Licensed to SEB Link A/S .

4.1 WCF service enhancements Connecting to a WCF service is accomplished in the same way as connecting to any other SOAP ERROR HANDLING One of the nice things about WCF is the ability to throw exceptions on a service call.Using advanced services 185 6.thiesen@seb. Unfo Snippet 6.Henrik Thiesen <henrik. out MyErrorObject myError).4 Using advanced services You’ve seen how to download data and various ways to parse the returned data streams into u 6.dk> .20 Reading an OUT parameter WCF SL [OperationContract] string GetSomeData(int Id. void serv Licensed to SEB Link A/S .

Error != null) { tbxMessage.Message. } if (e. let’s attach SL Licensed to SEB Link A/S .myError != null) { tbxMes In this snippet.Text = e.thiesen@seb. you see a standard [ServiceMethod]Completed method like those shown throug 6.dk> .Error.4.186 { CHAPTER 6 Networking and communications if (e.Henrik Thiesen <henrik.2 WCF duplex services So far we’ve talked about ways to send and receive data that require the Silverlight applic CONNECTING TO THE SERVICE Once you have a functioning WCF service set up to enable duplex communication.

22 Starting the process SynchronizationContext uiThread.21 Sample application to get score updates Result <Grid x:Name="LayoutRoot" Background="#FF6F93C3" Width="300"> <Button Height="41" Ho The only thing of note in the XAML is that the Click attribute of the button points to the Snippet 6.21 Snippet 6.Henrik Thiesen <henrik. RoutedEvent C# XML Licensed to SEB Link A/S . private void btnGetScores_Click(object sender.Using advanced services 187 Snippet 6.thiesen@seb.dk> .

we won t show the On[action]Completed methods because they all Snippet 6.CompletedSynchronously) return For the rest of this sample. you start the process of binding to a duplex web service.dk>   . You begin by cre Snippet 6.thiesen@seb.23 Example asynchronous handler void OnOpenFactoryComplete(IAsyncResult result) { if (result.22.188 CHAPTER 6 Networking and communications In snippet 6.24 Opening duplex channel and polling it void OpenTheChannel(IAsyncResult result) { IChannelFactory<IDuplexSessionChannel> channelFa C# Licensed to SEB Link A/S .Henrik Thiesen <henrik.

CreateMessage(channel.Using advanced services Message message = Message.GetProperty<MessageVersion>().25 Looking for messages void CompleteOnSend(IAsyncResult result) { IDuplexSessionChannel channel = (IDuplexSessionC The PollingLoop method assigns CompleteReceive (snippet 6. "Silverlight 189 The method OpenTheChannel in this snippet shows where you define the service you’re attempt Snippet 6.Henrik Thiesen <henrik.26) as the method to handle messa Licensed to SEB Link A/S .thiesen@seb.dk> .

190 CHAPTER 6 Networking and communications Snippet 6.Henrik Thiesen <henrik.thiesen@seb.dk> .26 Reading message void CompleteReceive(IAsyncResult result) { IDuplexSessionChannel channel = (IDuplexSession Creating and consuming a duplex-enabled WCF service take more effort than a standard SOAP s C# Licensed to SEB Link A/S .

dk> .Current C# XML Licensed to SEB Link A/S .4.Using advanced services 191 6.3 Connecting to sockets We’ve already discussed using a specially configured WCF service to enable push communicati Snippet 6.xml for socket access <?xml version="1.thiesen@seb.28 Snippet 6.28 Opening TCP socket public void OpenTheSocket() { DnsEndPoint tcpEndpoint = new DnsEndPoint(Application.27 clientaccesspolicy.Henrik Thiesen <henrik.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allo Opening a socket connection with a socket server can be done in a few simple steps that are Snippet 6.

C# Licensed to SEB Link A/S .28 shows the creations of an endpoint and a socket and using these to asynchronou Snippet 6.dk> .thiesen@seb.30.29 Handling response public void socketArgs_Completed(object sender.192 CHAPTER 6 Networking and communications Snippet 6. as shown in snippet 6. SocketAsyncEventArgs receivedArgs) { switch You can determine the type of response by evaluating the value of the LastOperation propert Value None Connect Receive Send Description Connection not yet established Connection estab SocketAsyncOperation enumeration Now you need to set up the connection to receive data.Henrik Thiesen <henrik.

5 Summary We know that at times this chapter has been complex and that some aspects of it may not see C# Licensed to SEB Link A/S .30 Receiving message public void ReceiveMessageOverSocket(SocketAsyncEventArgs receivedArgs) { string message = When the message comes in. it needs to be converted into the correct format.Henrik Thiesen <henrik.dk> . a string in th 6.Summary 193 Snippet 6.thiesen@seb.

Henrik Thiesen <henrik.Managing digital media This chapter covers ■ ■ ■ Interactive playback Playlist management Deep Zoom Chapter 6 introduced you to the rich and powerful communications framework found in Silverl 194 Licensed to SEB Link A/S .dk> .thiesen@seb.

microsoft.Henrik Thiesen <henrik.1 Stunning audio and video As you saw in chapter 1.com/winfx/2006/xaml/ Licensed to SEB Link A/S .dk> . I (Chad) will share an example from 7.1 XAML A MediaElement that uses relative syntax <UserControl x:Class="Snippet7_1.Page" xmlns="http://schemas.thiesen@seb.Stunning audio and video 195 illustrate how this type of impression can be achieved.1. integrating media into a Silverlight application is incredibly sim 7.1 Getting to the source The Source property of the MediaElement specifies the location of the audio or video file t Snippet 7.

196 CHAPTER 7 Managing digital media

Width="400" Height="300"> <Grid x:Name="LayoutRoot" Background="White"> <MediaElement x:Nam XAML B

This snippet shows a video that belongs to the same web application as the Silverlight appl Snippet 7.2 A MediaElement that uses absolute syntax

<UserControl x:Class="Snippet7_2.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/ XAML B

This snippet shows a video, which doesn’t include sound, being accessed from a remote serve SUPPORTED FORMATS

Have you ever wanted a snack or soda and accidently put foreign currency in your local vend 2

When developing Silverlight applications that use cross-domain URIs, you’ll need to run the Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Stunning audio and video 197 tained environment for media experiences. Once your users install the Silverlight runtime, STREAMING MEDIA

Table 7.1 The major media formats supported by the MediaElement Type Audio Audio Audio Vide Silverlight supports streaming media conVideo Windows Media Video 7, 8, 9 tent through the Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

198 THINKING PROGRESSIVELY CHAPTER 7 Managing digital media

Progressive downloading involves requesting a media file over the HTTP or HTTPS protocol. W Snippet 7.3 An example that shows the percentage of content ready for use within a MediaEle <UserControl x:Class="Snippet7_3.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/ XAML B C

using System; using System.Windows; using System.Windows.Controls; namespace Snippet7_3 { p C# D E F } Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Stunning audio and video 199

This snippet shows a large video file (~13MB) being progressively downloaded C. As this dow 7.1.2

Common properties The MediaElement provides a number of properties that are common to both audio and video fi AUTOPLAY

The AutoPlay property specifies whether or not the MediaElement will automatically begin pl CANPAUSE Sometimes you may want to allow a user to halt the playback of a MediaElement. By default, CURRENTSTATE The CurrentState property represents the mode the MediaElement is in. This mode is exposed Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

200 Table 7.2 CHAPTER 7 Managing digital media

The options available within the MediaElementState enumeration Option Description Occurs wh AcquiringLicense Buffering Closed Individualizing Opening Paused Playing Stopped

value is changed, an event called CurrentStateChanged is fired. The state of the media item NATURALDURATION

The NaturalDuration property gives you access to the natural duration of a media item. This Snippet 7.4 An example that shows the NaturalDuration of a MediaElement

void myMediaElement_MediaOpened(object sender, RoutedEventArgs e) { myTextBlock.Text = "You B C

This snippet displays the total length of a media item in an assumed TextBlock. This task t C# Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Stunning audio and video 201

MediaElement, this property value will always be true, enabling you to access highly detail Snippet 7.5 An example that shows the NaturalDuration of a MediaElement void myMediaElement_MediaOpened(object sender, RoutedEventArgs e) { StringBuilder sb = new This snippet shows how to access detailed information about the length of a media item. As POSITION

The Position property represents a point, or location, within a MediaElement. This value ca 7.1.3

Audio specifics The MediaElement exposes several properties that are directly linked to audio features. The C# Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

202 CHAPTER 7 Managing digital media AUDIOSTREAMCOUNT/AUDIOSTREAMINDEX

Occasionally, audio or video files will contain more than one audio track. As an example, a BALANCE

The Balance property enables you to effortlessly simulate sounds like a wave gently lapping ISMUTED

Personally, when I (Chad) am working, I usually listen to music through my computer. For th Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Stunning audio and video 203

MediaElement is audible. If a MediaElement is playing and this Boolean property is set to t VOLUME The Volume property is a double-precision, floating-point value that specifies the audible 7.1.4

Video specifics The MediaElement exposes four properties directly related to videos. In reality, there is a 7.1.5

The lifecycle of a media file Throughout this section, you’ve seen a wide variety of properties. Some of these property v Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

dk> .3 CHAPTER 7 Managing digital media The events of the MediaElement Event Description Triggered anytime the BufferingProgress pr BufferingProgressChanged CurrentStateChanged DownloadProgressChanged MarkerReached MediaEnded MediaFailed MediaOpened This table shows the events exposed by the MediaElement.thiesen@seb.1 The cycle of events as a media item plays progressively within a MediaElement Licensed to SEB Link A/S .204 Table 7.Henrik Thiesen <henrik. Note that some state changes trigg Figure 7.

6 XAML A MediaElement referencing a client-side playlist <MediaElement x:Name="myMediaElement" Source="http://www.2.Playlists: for that web-based mixtape 205 If you reference a media item that can’t be found. the MediaFailed event will fire. These 7.1 Understanding client-side playlists A client-side playlist is an XML file that can be interpreted by a MediaElement.dk> .thiesen@seb. but the 7. Note that this playlist uses the Licensed to SEB Link A/S .2 Playlists: for that web-based mixtape A playlist is a list of audio or video tracks that are arranged in a specific order.silverlightinaction.com/myPlaylist This snippet shows how to request a client-side playlist.Henrik Thiesen <henrik. This XML f Snippet 7.

surrounding each of the tracks. known as metadata. These files can have rich.thiesen@seb.0"> <Title>Silverlight in Action Videos</Title> <Entry> <Title>Greetings</T This snippet shows a pretty basic client-side playlist that uses a small portion of the ful Table 7.dk> . USING ASX FILES Client-side playlists are defined as Advanced Stream Redirector (ASX) files—this is just a Snippet 7.7 An example of an ASX file <ASX Version="3.206 CHAPTER 7 Managing digital media ASX files. descriptive information.Henrik Thiesen <henrik.4 The ASX elements supported within Silverlight Description Provides a description XML Element Abstract Asx Author Base Copyright Entry Licensed to SEB Link A/S .

an ASX fi ACCESSING THE METADATA The metadata for a media item can be found within a read-only property called Attributes.dk> .2. and whe ■ Lower bandwidth costs—Generally client-side playlists serve content as separate streams for Licensed to SEB Link A/S .Playlists: for that web-based mixtape Table 7. As you can see.2 Using server-side playlists Server-side playlists empower content administrators to dynamically determine what. T 7.4 The ASX elements supported within Silverlight (continued) Description 207 Element MoreInfo Enables you to specify a URL that provides more detailed information about the playlist or Param Ref Title This table shows the ASX elements supported within Silverlight 2.Henrik Thiesen <henrik.thiesen@seb.

you must write a script using the Synchronized Multime CREATING WSX FILES Server-side playlists are defined as .thiesen@seb.Henrik Thiesen <henrik.8 A sample WSX file <?wsx version="1. wasting precious bandwidth. Because server-side playlists use a To take advantage of these features. This snippet shows a basic . This playlist uses three of the elements supported by Table 7.0"?> <smil> <seq id="sq1"> <media id="advertisement1" src="advertisement1.5 Element Excl The SMIL elements supported within Silverlight Description A contain XML Media Seq Smil Switch Licensed to SEB Link A/S .dk> .wsx file.208 CHAPTER 7 Managing digital media ■ the server multiple times. These files are XML files that follow a sp Snippet 7.wsx files.

you can publish it on your server. You may hav 7.Henrik Thiesen <henrik. Silverlight makes it easy to deploy media content with the 7.dk> .3.thiesen@seb.Interactive playback REFERENCING SERVER-SIDE PLAYLISTS 209 After your .3 Interactive playback As you’ve seen up to this point.silverlightinaction.9 XAML Referencing a server-side playlist. Note: This stream doesn’t actually exist. <MediaElement Source="mms://www.1 Controlling the play state The MediaElement gives you ability to programmatically change the play state of a media ite Licensed to SEB Link A/S .wsx file has been created. You must publish Snippet 7.com:1234/myPlaylist" /> This snippet shows how to reference a server-side playlist from a MediaElement.

you probably expected the ability t 7.2 Timely interaction The MediaElement enables you to interact with your users at specific points in time. This c Licensed to SEB Link A/S .dk> .210 Table 7. In addition.thiesen@seb.3.6 Method Play CHAPTER 7 Managing digital media The methods that control the progress of a MediaElement Description Begins moving the Posit Pause Stop stop a media item before seeing this list.Henrik Thiesen <henrik.

7 Property Text The properties associated with a TimelineMarker Description A value Time Type the majority of other collections in Silverlight.10 A sample of using the MarkerReached event to show a caption on a MediaElement <Canvas x:Name="myCanvas"> <MediaElement x:Name="myMediaElement" Source="http://www.thiesen@seb.silverl XAML B C D This snippet shows one way you can use the MarkerReached event B. This event provides a Tim C# Licensed to SEB Link A/S .Interactive playback 211 file. the metadata within the header of the file is used to create Tim Table 7. During this process.dk> .Henrik Thiesen <henrik. because the markers come from the media i Snippet 7.

dk> .Henrik Thiesen <henrik. The Licensed to SEB Link A/S .212 CHAPTER 7 Managing digital media 7. The first mode is called em Embedded mode Full-screen mode Figure 7.3 Going full screen In keeping with the promise of delivering rich interactive experiences.2 The difference between embedded and fullscreen modes This figure shows the same Silverlight application running in the two different modes.thiesen@seb. Silverlight goes fa UNDERSTANDING THE SCREEN MODES Silverlight enables you to view content in two different modes.3.

4 Using protected content The interactive playback features within Silverlight can be used to give your users an enga Licensed to SEB Link A/S .Using protected content 213 wise sensitive information such as bank account numbers and passwords.Current.Host. This snippet shows how to switch a plug-in into full-screen mode.11 Switching a plug-in into full-screen mode C# Application.IsFullScreen = true.Content.Henrik Thiesen <henrik.thiesen@seb. Because of the sever TOGGLING BETWEEN SCREEN MODES The SilverlightHost class gives you access to the information associated with a plugin inst Snippet 7. As you probably already g 7.dk> .

Henrik Thiesen <henrik. This overview 7. Silverlight 2 has the infrastructure for PlayReady.4.214 CHAPTER 7 Managing digital media section.4.1 Requesting protected content A Silverlight application can request protected content.thiesen@seb.2 Retrieving the PlayReady components By default.dk> . but the PlayReady component Licensed to SEB Link A/S . you’ll see an overview of how Silverlight uses PlayReady technology. which may be in the form of a prot 7.

5 Using images in your application Images are used on web pages all across the internet.thiesen@seb. it’s still encry 7.Using images in your application 215 the content is still locked (as shown in figure 7.4.3 Unlocking protected content Once a protected item has been downloaded to your Silverlight application. They’re used in the form of applicati Licensed to SEB Link A/S .Henrik Thiesen <henrik.5). a request mus 7. To unlock this content.dk> .

Henrik Thiesen <henrik.dk> .com domain.2 Deep Zoom Deep Zoom is a feature of Silverlight that empowers a user to explore groupings of high-res XAML Licensed to SEB Link A/S . The Image in this snippet retrieves an image from the silverlightinaction. These formats are inherentl This table shows the image formats supported by the BitmapImage class.silverlightinaction. Because this is the 7.thiesen@seb. In addition to l Snippet 7.216 CHAPTER 7 Managing digital media 7.5.8 The image formats supported by the BitmapImage class.1 Basic imaging The Image element empowers you to display images from across the internet. This Table 7.12 An Image that uses a picture from another domain Result <StackPanel Height="200" Width="100"> <Image Source="http://www.5.

Using images in your application 217 is associated with painful wait times because high-resolution images are generally larger i SHOWING AN IMAGE Showing an image within a MultiScaleImage control is nearly identical to showing an image w Snippet 7.dk> .Henrik Thiesen <henrik.xml" /> This snippet shows the XAML to load a relative multiscale image at design time.x This snippet shows how to load a multiscale image at runtime.13 Referencing a relative multiscale image in XAML XAML C# <MultiScaleImage x:Name="myMultiScaleImage" Source="images/dzc_output. If the referenced image can’t Licensed to SEB Link A/S .14 Referencing a relative multiscale image at runtime myMultiScaleImage.thiesen@seb. In the even Snippet 7.Uri("images/dzc_output.Source = new DeepZoomImageTileSource( new System.

els E This snippet looks like a lot of code. In short. this. point. this code empowers a user to zoom in or ou Licensed to SEB Link A/S .ZoomAboutLogicalPoint(1.5.dk> . point. A zoom-out will occur if the user presses S public Page() { InitializeComponent().15 Implementing a zoom functionality. KeyEventArgs e) { if (e.thiesen@seb.KeyDown += new KeyEventHandler(Page_KeyDown). MouseButtonEventArgs e) { Point p if (shouldZoom == true) myMultiScaleImage. void Page_KeyDown(object sender. t B C D } private bool shouldZoom = true. Thi Snippet 7.218 ZOOMING IN AND OUT CHAPTER 7 Managing digital media The MultiScaleImage control has the ability to show an extremely high-resolution image.X. B C# C D void myMultiScaleImage_MouseLeftButtonDown(object sender.Y).Henrik Thiesen <henrik.

9 Method Coordinate-system conversion methods Description ElementToLogicalPoint Converts a Cartesian Point to a logical Point. the zooming feature Table 7.Using images in your application 219 ing to zoom away from the image. This is generally used Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik.thiesen@seb. If the Shift key hasn’t been pressed.

As you migh Licensed to SEB Link A/S . This region Snippet 7.dk> .thiesen@seb. Notice the syntax of the ViewportOrigin p XAML <MultiScaleImage x:Name="myMultiScaleImage" Source="images/dzc_output.220 MANAGING THE VIEWPORT CHAPTER 7 Managing digital media The viewport is a rectangular region used to view a specific area of an image.Henrik Thiesen <henrik.xml" ViewportOri This snippet shows how to set the ViewportOrigin property value at design time.16 Defining the ViewportOrigin in XAML.

These two items m Licensed to SEB Link A/S .Henrik Thiesen <henrik. MouseButtonEventArgs e) { Point new This snippet shows how to reposition the ViewportOrigin based on where a user clicked.dk> .xml file and a file/folder structure.thiesen@seb.Using images in your application 221 Snippet 7. Notice the syntax of the ViewportOrigin pro void myMultiScaleImage_MouseLeftButtonUp(object sender. Once DEPLOYING MULTISCALE IMAGES The MultiScaleImage control has built-in support for handling XML that details a multiscale 1 2 3 C# Import—Enables you to import your own images.17 Defining the ViewportOrigin in C#. Compose—Empowers you to lay out how the image These three steps will generate an .

dk> .6 The 7th inning stretch: Dealing with dead space Throughout this chapter you’ve seen a variety of ways to deliver different kinds of media. Raster-based graphics of Licensed to SEB Link A/S . photos are represented as raster-based graphics. Figure 7.Henrik Thiesen <henrik.222 CHAPTER 7 Managing digital media Deep Zoom is a powerful feature available within Silverlight. Because this technology relie 7.thiesen@seb.1 I’ll have none of this stretching business Most of the time.6.8 The boundary of an Image element in comparison to the actual size of the photo The Image. MediaElement. and Shape (discussed in the next chapter) classes expose a propert 7.

18 Use of the None option on an adequately sized Image element XAML XAML Result <Image x:Name="myImage" Width="75" Height="75" Source="http://www.thiesen@seb. the content of the element will symmetrically e Licensed to SEB Link A/S . the or 7.The 7th inning stretch: Dealing with dead space 223 Snippet 7.Henrik Thiesen <henrik.19 Use of the None option on an adequately sized Image element Unfortunately for Walker.6.dk> . The result from th Snippet 7. his legs got cut off! As the result in this snippet shows.silverli The XAML in this snippet loads an Image and prevents it from stretching.2 Uniform sizing If you set the Stretch property to Uniform.

22 An image using the Fill option to stretch an Image Result XAML XAML <Image x:Name="myImage" Width="75" Height="75" Source="http://www. although the Fill option will expand Licensed to SEB Link A/S . as 7.20 A uniformly stretched Image with a photo smaller than the element Result XAML Result <Image x:Name="myImage" Width="300" Height="200" Source="http://www. the content of an element to fully occup Snippet 7.com/m <Image x:Name="myImage" Width="300" Height="200" Source="http://www.Henrik Thiesen <henrik.silverlightinaction. or contract.6. Instead of cropping the image.silv The gray backdrop in this snippet represents the area that could be filled by an image.com Walker looks a little bloated in this snippet because.3 Fill the area The Fill option allows you to expand. Bec Snippet 7.thiesen@seb.silverlightinaction. the content remains intact.dk> .21 A uniformly stretched Image with a photo larger than the element As this snippet illustrates.224 CHAPTER 7 Managing digital media Snippet 7.

Henrik Thiesen <henrik.7 Summary Over the course of this chapter.4 UniformToFill As the name implies.thiesen@seb. Because of the oblong dimensions of the photo. The cont Snippet 7.silverlight This snippet illustrates how a raster-based graphic can become pixilated when inflated. the photo is str 7. It 7.6.23 An Image using the UniformToFill Stretch option Result XAML <Image x:Name="myImage" Width="300" Height="200" Source="http://www. you saw the rich media features available within Silverlig Licensed to SEB Link A/S .Summary 225 content won’t be preserved. this option is a hybrid between the Uniform and Fill options.dk> .

Getting a grip on graphics This chapter covers ■ ■ ■ Creating basic shapes and geometries Painting with brushes Changing UIElement objects with Silverlight’s extensive multimedia support enables you to create internet-based experiences 226 Licensed to SEB Link A/S .dk> .thiesen@seb.Henrik Thiesen <henrik.

Henrik Thiesen <henrik.thiesen@seb.1 Getting in shape Shapes are probably the most regularly used elements when creating an illustration because Licensed to SEB Link A/S .dk> .Getting in shape 227 joyful expressions will come from users who have emerged from a fog of confusion that was l 8.

1 Result A basic Line There are four double-precision floating-point properties (X1.228 Table 8. you’ll learn 8. a continuous line that connects two end points. First. X2.1 shows a b Snippet 8. Snippet 8. Y1. continuous mark that co Element Line Ellipse Path Polygon Polyline Rectangle of a more general category that will be covered later in this chapter.Henrik Thiesen <henrik. obviously.thiesen@seb. Description A thin.dk> .1 CHAPTER 8 Getting a grip on graphics The Shape objects available within Silverlight.1.1 A Line in the sand A Line is. Y2) that specify the XAML <Canvas x:Name="myCanvas" Height="20" Width="50"> <Line Stroke="Black" X1="10" Y1="10" X2=" Licensed to SEB Link A/S .

Top="8" RadiusX="1 The RadiusX and RadiusY double-precision floating-point properties allow you to set the rad Snippet 8.Left="8" Canvas.dk> .2 Result A basic Rectangle XAML <Rectangle Stroke="Black" Width="104" Height="64" Canvas.Top="8"/> This snippet shows an archetypal Rectangle.Left="8" Canvas.2 Rectangle A Rectangle does exactly what its name implies—it defines a rectangle. The key properties involved in the definition o Snippet 8.3 Result A Rectangle with rounded corners XAML <Rectangle Stroke="Black" Width="104" Height="64" Canvas.thiesen@seb.Henrik Thiesen <henrik.Top="8" RadiusX="1 Licensed to SEB Link A/S .4 Result A bulging rectangle XAML <Rectangle Stroke="Black" Width="104" Height="64" Canvas.Left="8" Canvas.1. The Rectangle within Snippet 8.Getting in shape 229 8.

5 Result The syntax and look of a basic Ellipse XAML <Ellipse Stroke="Black" Width="104" Height="64" Canvas.4 Polyline What if you need to create an application that represents an EKG (or ECG) monitor? How woul Snippet 8.49 40.1.Henrik Thiesen <henrik. A Licensed to SEB Link A/S .thiesen@seb. But occasionally.12 46.3 The ellipse An Ellipse defines a basic circular shape. The diff 8. you may need a fully rounde 8.44 25. Snippet 8.5 shows a basic Ellipse and the XAML u Snippet 8.50 51.50 20.dk> .42 55.50" /> The Polyline uses a space-delimited list of coordinate pairings to define the line drawn.40 23.1.6 Result A Polyline XAML <Polyline Stroke="Black" Points="10.Left="8" Canvas.Top="8"/> The Ellipse doesn’t provide any properties that distinguish it from the Rectangle.230 CHAPTER 8 Getting a grip on graphics The bulging Rectangle is a fun little option.

10 70.40" /> Like the sibling Polyline. the Polygon also utilizes the Points property.7 Result A basic Polygon in action XAML <Polygon Stroke="Black" Points="10.thiesen@seb.10 70.5 Polygon The Polygon goes one step beyond the Polyline by ensuring the Shape is always closed.40" /> The available shapes provide a lot of flexibility to give your users valuable graphical exp 8.40 10.10 60. This property wor Snippet 8.40 20.2 Geometry At first.40 20.10 70. a Geometry seems similar to a Shape because they both describe 2D shapes.40 20.1. A Pol Snippet 8. Unlike XAML Licensed to SEB Link A/S . each Point within the list is relative to the 8.10 60.dk> .Geometry 231 property.8 Type An open shape compared to a closed shape Closed Shape Polygon Open Shape Polyline Result <Polyline Stroke="Black" Fill="White" Points="10.40" /> <Polygon Stroke="Black" Fill="White" Points="10.10 60.Henrik Thiesen <henrik. In being consistent with the Line.

imagine creating a user-based rating system.8" EndPo Line XAML Path XAML From this snippet. suc ■ ■ ■ Define a geometric shape.Henrik Thiesen <henrik. In this These compelling reasons make examining the Geometry object a worthwhile endeavor.thiesen@seb.dk> . For example. A Geomet 8. But you Licensed to SEB Link A/S .2.232 CHAPTER 8 Getting a grip on graphics objects have an intrinsic ability to render themselves and expose graphical properties.Data> <LineGeometry StartPoint="8.1 Simple geometries A simple geometry reflects some of the primitive geometrical shapes that you’ve already see Snippet 8. you can see that using the Line Shape XAML is much more compact.9 Result Comparison between the Line and LineGeometry <Path Stroke="Black" StrokeThickness="1" > <Path.

2 Elipse XAML Path XAML As useful as lines.thiesen@seb.Henrik Thiesen <henrik.Data> <RectangleGeometry Like the Rectangle Shape. and circles are.dk> . rectangles. the RectangleGeometry also supports corner-rounding via the Radiu Snippet 8.11 An EllipseGeometry compared to an Ellipse 8.2. you need to create a more dy Path geometries A PathGeometry empowers you to construct complex. occasionally. detailed illustrations composed of a vari Licensed to SEB Link A/S .Geometry 233 Snippet 8.10 A RectangleGeometry compared to a Rectangle Result <Path Fill="Navy" Stroke="Black" StrokeThickness="1"> <Path.

234 CHAPTER 8 Getting a grip on graphics Snippet 8.2 The list of available segment types. Segment Type LineSegment PolyLineSegment Arc XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik.12 A PathGeometry Result <Canvas Width="100" Height="100" Background="Gray"> <Path Stroke="Red" StrokeThickne This snippet uses five different segment types to create random squiggles. Each individual Table 8.thiesen@seb.dk> .

13 A composite geometry to make a key Result <Path Stroke="Navy" StrokeThickness="8" Fill="Navy"> <Path.2.3 Brushes Up to this point. you’ve seen how to define the boundaries of the various Shape elements.3 Composite geometries You may need to create a complex shape that consists of disconnected entities.Data> <GeometryGroup Fill This snippet illustrates how to create a key using a complex geometry via the GeometryGroup 8.thiesen@seb. Or. I XAML Licensed to SEB Link A/S . you may Snippet 8.Brushes 235 8.dk> .Henrik Thiesen <henrik.

Windows.thiesen@seb.Media.1 SolidColorBrush The SolidColorBrush is without a doubt the most rudimentary of the Brush options.14 A basic SolidColorBrush in action Result <Ellipse Stroke="Black" StrokeThickness="3" Width="64" Height="64" Canvas.Henrik Thiesen <henrik.15 The alternative approach to the SolidColorBrush <Ellipse Stroke="Black" StrokeThickness="3" Fill="Navy" Width="64" Height="64" Canvas. that matches one of the names supported within Inte These color options give you a lot of flexibility when you’re defining a SolidColorBrush. it’s still important to remember the SolidCo Licensed to SEB Link A/S . I Snippet 8.Color property named Color to specify whic ■ XAML XAML ■ ■ A predefined named color.Left= Although this explicit approach is convenient.Left="8" C This SolidColorBrush uses a System. such as Navy. A SolidCo Snippet 8.236 CHAPTER 8 Getting a grip on graphics 8.3.dk> .

thiesen@seb.Left="8" C This Ellipse illustrates how the LinearGradientBrush can be used to shift from Navy in the XAML Licensed to SEB Link A/S . Silverlight 8.16 A basic LinearGradientBrush rendered diagonally Result <Ellipse Stroke="Black" StrokeThickness="3" Width="64" Height="64" Canvas.Henrik Thiesen <henrik.3.dk> .Brushes 237 you may want something richer and more vibrant than a solid color.2 LinearGradientBrush The LinearGradientBrush paints an area with a gradual. soothing shift between colors along Snippet 8. Thankfully.

238 CHAPTER 8 Getting a grip on graphics instead of diagonally. This can be accomplished by altering the StartPoint and EndPoint pro Snippet 8.Left="8" Canvas.thiesen@seb.dk> .Left="8" C Although you could have rotated the imaginary gradient line by altering the Offset property Snippet 8.17 A basic LinearGradientBrush rendered horizontally Result <Ellipse Stroke="Black" StrokeThickness="3" Width="64" Height="64" Canvas.18 A horizontal LinearGradientBrush with multiple transitions Result <Rectangle StrokeThickness="0" Width="200" Height="64" Canvas.Henrik Thiesen <henrik. the LinearGradientBrush provides you with a lot of opp XAML XAML Licensed to SEB Link A/S .Top="8 As the previous snippets have shown.

This origi Snippet 8.Fill> <RadialGradientBrush> As this snippet shows.3 RadialGradientBrush The RadialGradientBrush is very similar to the LinearGradientBrush except that the color tr Snippet 8.19 A basic RadialGradientBrush Result <Ellipse Width="75" Height="75" Stroke="Black"> <Ellipse.dk> .Brushes 239 8.thiesen@seb.Henrik Thiesen <henrik.3.20 Comparing various uses of the RadiusX and RadiusY properties of the RadialGrad Result <Canvas Width="245" Height="75" Background="White"> <Ellipse Width="75" Height="75" XAML Licensed to SEB Link A/S . the brush begins at the center of the Ellipse by default.

Fill> <ImageBrush ImageSour As you can imagine.Le As the previous snippets show.dk> . an ImageBrush can easily add a rich.Fill> </Ellipse> <Ellipse Width="75" Height="75" Canvas.thiesen@seb.240 CHAPTER 8 Getting a grip on graphics </RadialGradientBrush> </Ellipse. vibrant touch to your painting sur XAML XAML Licensed to SEB Link A/S .4 ImageBrush The ImageBrush allows you to fill an area with an image instead of a solid or shifting colo Snippet 8.Henrik Thiesen <henrik. you can use a GradientBrush to provide basic linear and radi 8.3.21 An example of an ImageBrush Result <Ellipse Width="60" Height="60" Stroke="Black"> <Ellipse.

thiesen@seb.3.Brushes 241 livelier.dk> .silverlightinaction. With the same type of simplicity as the ImageBrush.5 VideoBrush Imagine watching a shooting star speed across the night sky through the elliptical eyepiece Snippet 8. All XAML XAML Licensed to SEB Link A/S .co This sample only begins to show the potential allotted by the different Brush elements.23 An example of a VideoBrush within a TextBlock <MediaElement x:Name="myMediaElement" Opacity="0" Source="http://www.Henrik Thiesen <henrik.silverlightinaction.22 An example of a VideoBrush <MediaElement x:Name="myMediaElement" Opacity="0" Source="http://www.co As this snippet shows. the VideoBrush references a MediaElement through the SourceName prop Snippet 8. you can paint a surface with 8.

Henrik Thiesen <henrik.24 A square that has been rotated by 30 degrees Result <Rectangle Width="50" Height="50" Fill="Green" Stroke="Black"> <Rectangle.1 RotateTransform The RotateTransform is responsible for rotating an object clockwise around a specified poin Snippet 8.3 describes.RenderTran The Angle property specifies to rotate clockwise around the optional CenterX and CenterY pr XAML Licensed to SEB Link A/S .4.4 Transforms The Transform element gives you the flexibility to alter the appearance of any UIElement wi Table 8.thiesen@seb.3 A list of the available transformation options Transform RotateTransform ScaleTra As table 8. As you’ll see within ea 8. each Transform has its own special purpose.dk> .242 CHAPTER 8 Getting a grip on graphics 8.

Henrik Thiesen <henrik.3 SkewTransform A SkewTransform warps the coordinate space in a divergent manner. If you set these values to the center of 8.25 A square that has been scaled by a magnitude of 2. or shearing.thiesen@seb.dk> .2 ScaleTransform The ScaleTransform enables you to expand or contract an object horizontally or vertically. As you may expe 8.4.5 Result <Rectangle Width="30" Height="30" Fill="Green" Stroke="Black" Canvas.Left="35" Canva The ScaleX and ScaleY properties determine the magnitude to zoom in/out by. Snippet 8.Left="12" XAML Licensed to SEB Link A/S .4. Snippet 8.Transforms 243 element will rotate around the upper-left corner. By skewing.26 A Rectangle that has been skewed by 18 degrees Result XAML <Rectangle Width="75" Height="75" Fill="Green" Stroke="Black" Canvas.

4 TranslateTransform The TranslateTransform element allows you to define how to transfer an element from one loc Snippet 8.Henrik Thiesen <henrik.244 CHAPTER 8 Getting a grip on graphics <TransformGroup> <SkewTransform AngleX="18" AngleY="18"/> </TransformGroup> </Rectangle.4.27 A basic translation in action Result <Rectangle Width="50" Height="50" Fill="Green" Stroke="Black"> <Rectangle.thiesen@seb. you may have noticed the TransformGroup element XAML XAML Licensed to SEB Link A/S .dk> .RenderTran As this snippet demonstrates.Ren The AngleX and AngleY properties specify the amount to shear the rectangle horizontally and 8.4.5 TransformGroup In the previous transform-related examples. by specifying a double-precision floating-point value within 8.

Licensed to SEB Link A/S .5 Blending it together Throughout this chapter. you’ve learned about Silverlight’s rich graphical capabilities. Notice how the content of the Result <TextBox x:Name="myTextBox" Height="30" Width="90"> <TextBox. Select File > New Project… From the New Project Dialog. it does accurately display the true flexibility a 8.thiesen@seb.Henrik Thiesen <henrik.Blending it together 245 Snippet 8. In XAML Figure 8.dk> .2 The end result of this Blending it Together section. Walk-through 8.1 1 2 3 Creating an ellipse within Expression Blend 2 Launch Microsoft Expression Blend.28 A sample of all of the transforms on a TextBox.RenderTransform> <Trans Although this snippet is a bit excessive.

Licensed to SEB Link A/S .246 CHAPTER 8 Getting a grip on graphics 4 From the toolbox. the properties associated with the ellipse will be displayed. draw an ellipse on the LayoutRoot within the Page.thiesen@seb. From the upper-left corner of the LayoutRoot. With the Ellipse tool selected.dk> .xaml tab. The Properties tab is located within the upper-right corner of Blend. hold down the left mouse button and drag down 6 Continue to drag the mouse until the ellipse has a height and width of approximately 100. along the left side of the screen. Open the Properties panel by selecting the Properties tab in the upper-right corner of Blen When selected. T When done. your ellipse should look similar to this.Henrik Thiesen <henrik. 5 Select the "Ellipse" tool. expand the Shape Tools option list and Click and hold down the "Rectangle" tool to expand the "Shape tools" option list.

10 11 12 With the UserControl element selected. you need to add some dimension to make it look like Walk-through 8.thiesen@seb. enter myEllipse. go to the Properties panel (along the right side of Now that the ellipse has been created.1 open.Blending it together 7 8 247 9 Within the Name field. select the myEllipse element from th Licensed to SEB Link A/S . Toward the bottom of the Properties panel is the La Click the Page item to select the root Canvas.2 1 Turning an ellipse into a ball within Expression Blend 2 2 With the project created within walk-through 8. Locate the Objects and Timeline category within Blend.dk> .Henrik Thiesen <henrik.

Select the Radial Gradient brush within the lower-left corner of the Brushes category. the Solid Color Brush is selected. Select the Radial Gradient within the lower-left corner of the Brushes category. 6 Change the leftmost gradient stop within the gradient slider to White. By default.Henrik Thiesen <henrik. 5 Click the Gradient Brush tab. 3 4 Select the Fill brush.thiesen@seb.248 CHAPTER 8 Getting a grip on graphics The Brushes category is located toward the top of the Properties panel.dk> . Select the Gradient Brush tab. (It will automatical Licensed to SEB Link A/S .

you have something that looks much richer and vibrant. 7 Click the rightmost gradient stop. Firs The Brush Transform tool is located within the toolbox. click the opening end of the transform arrow and dr Drag the open end of the transform arrow to the lower-right corner or the ellipse. Once completed.Henrik Thiesen <henrik. At this point. which is located on the far left si 9 With the Brush Transform tool selected.Blending it together 249 Click the leftmost gradient stop. Let’s now turn our fo Licensed to SEB Link A/S . 10 Once in the lower-left corner. your ellipse will look like this. Press F5 to run the application.thiesen@seb. rotate the transformation to the 10 o’clock position. and then change the value to Navy. and then change the value to White.dk> . At this point. your ellipse should look like the following: 8 Now let’s transform the fill to make the ball look like there’s a light shining on it.

// Initialize th Licensed to SEB Link A/S .Angle = 0. rotateTransform.3 1 2 Adding event handlers to the ball in Visual Studio 3 4 Launch Microsoft Visual Studio 2008.Henrik Thiesen <henrik.thiesen@seb. Select File > Open > Project/Solution…. within the constructor of the class.dk> . place calls to the three previously defined metho public Page() { // Required to initialize variables InitializeComponent().250 CHAPTER 8 Getting a grip on graphics Walk-through 8.0. and select the // The transformation to increase/decrease the ball by private ScaleTransform scaleTransfor 5 Add the following method to the class to define the initial amount the ellipse is scaled by private void InitializeScaleTransform() { // Set the inital scale at nothing scaleTransform 6 Add the following method to the class to define the initial rotation and specify that you w private void InitializeRotateTransform() { rotateTransform.Cen 7 Add the following method to the class to connect the transformations to the ellipse: private void InitializeTransformGroup() { TransformGroup transformGroup = new TransformGrou 8 Now.

2. you should have a ball that resembles that in figure 8. Within the UserControl element. add an event handler for the KeyDo private void UserControl_KeyDown(object sender. Licensed to SEB Link A/S .Summary InitializeScaleTransform(). } 9 10 251 Open the Page. KeyEventArgs e) { if (e.xaml file. InitializeTransformGroup().Key == Key.6 Summary Silverlight’s inherent graphical capabilities go far beyond cartoons and visual fireworks. At this point.thiesen@seb.dk> .Henrik Thiesen <henrik.A) // AKeyDown="UserControl_KeyDown" 11 12 13 Press F5 to run the application. Although fairly tr 8. InitializeRotateTransform().

thiesen@seb.252 CHAPTER 8 Getting a grip on graphics Although the rich graphical capabilities are incredibly valuable and immersive.dk> .Henrik Thiesen <henrik. there is on Licensed to SEB Link A/S .

Bringing it to life: Animation This chapter covers ■ ■ ■ Creating animations Providing interactive animations Using key frames The illuminating graphical capabilities described in chapter 8 laid the groundwork for crea 253 Licensed to SEB Link A/S .Henrik Thiesen <henrik.dk> .thiesen@seb.

imagine meeting someone for the first time. Your initial conversation may 9.254 CHAPTER 9 Bringing it to life: Animation trate this value.thiesen@seb.dk> .1 Animation: It’s about time An animation within Silverlight boils down to changing a single visual property over some p Licensed to SEB Link A/S .Henrik Thiesen <henrik.

This action is represented as the BeginStoryboard element. A lot of new element B The EventTrigger element initiates an action when the Image is loaded.Henrik Thiesen <henrik.silverlightinaction.1 XAML for fading in an Image over course of one second <Image x:Name="myImage" Source="http://www. You create this dramatic animation by using the code in snippet 9.Trigger B XAML C D This snippet shows the XAML responsible for fading an image into view. C The Storyboard object is responsible for organizing and controlling the animations defined within it.Animation: It’s about time 255 Figure 9.1 An image fading into view over the course of one second Image gradually becomes more and more opaque. this Storyboard is automatically D The DoubleAnimation element specifies that you’re going to animate a double-precision val Licensed to SEB Link A/S .dk> .png"> <Image.1. Because of the BeginStoryboard action.com/man. Snippet 9.thiesen@seb.

microsoft.1.thiesen@seb.2 The XAML for a basic Ellipse <UserControl x:Class="EllipseAnimation. there are a significant number of details surr 9. you first select a single visual attribute of a single element. This timeline demonstrates how central the concept of time is to a 9.2.com/winfx/2006 XAML B Licensed to SEB Link A/S .dk> . Thi Snippet 9. every animation represents a Timeline object. and where are you goi Although these questions sound fairly basic.Henrik Thiesen <henrik.256 CHAPTER 9 Bringing it to life: Animation one shown in figure 9. This object is defined within th ■ ■ ■ What type of property are you animating? Where are you starting from.Page" xmlns="http://schemas.1 What type of property are you animating? To create an animation.2 Mastering the timeline At its base.

delivering a fade effect is incredibly simple.3 XAML The XAML for animating a double-precision floating-point number <DoubleAnimation Storyboard. This Ellipse will be used in the remainder DOUBLEANIMATION A DoubleAnimation enables you to animate a single property value from one doubleprecision f Snippet 9.TargetName="myEllipse" Storyboard. The DoubleAnima POINTANIMATION The PointAnimation type enables you to animate from one pair of x-and-y coordinates to anot Licensed to SEB Link A/S .Henrik Thiesen <henrik.Mastering the timeline 257 This snippet shows an Ellipse named myEllipse B.TargetProperty="Opacity" From As this snippet illustrates.thiesen@seb.dk> .

2 Where are you starting from and where are you going? As figure 9.2. an animation usually has a beginning and an end. These Snippet 9.258 CHAPTER 9 Bringing it to life: Animation Snippet 9.Henrik Thiesen <henrik.TargetName="myEllipse" Storyboard.thiesen@seb.dk> .TargetProperty="RenderTransformOrigin" Storyboard.TargetProperty="(Fill). Licensed to SEB Link A/S . The end of an a WHERE IS THE ANIMATION COMING FROM? There is a saying that you can’t know where you’re going until you know where you’ve been.TargetName="my The animation in this snippet changes the origin of any transforms applied to the Ellipse i COLORANIMATION A ColorAnimation empowers you to create smooth transitions from one color to another.4 XAML XAML for animating pair of x-and-y coordinates <PointAnimation Storyboard.(SolidC This snippet shows an assumed Ellipse shifting from “Yellow” to “Red” over the course of on 9.5 XAML XAML for shifting between colors <ColorAnimation Storyboard.1 illustrated.

This val Snippet 9.TargetName="myImage" Storyboard.Mastering the timeline 259 The From property is accessible from all the animation types that we’ve discussed.6 XAML XAML demonstrating From property within DoubleAnimation <DoubleAnimation Storyboard.Henrik Thiesen <henrik.dk> . it automatically determines that the Opacity val Licensed to SEB Link A/S .thiesen@seb.TargetName="myImage" Storyboard.TargetProperty="Opacity" To="1" When the animation in this snippet begins.7 XAML XAML demonstrating absence of From property within DoubleAnimation <DoubleAnimation Storyboard. The Opacity Snippet 9.TargetProperty="Opacity" From=" This snippet is preparing to animate the Opacity property of an assumed Image.

The To p Snippet 9. the Opa Snippet 9.TargetName="myImage" Storyboard.dk> .thiesen@seb. When the animation begins.TargetProperty="Opacity" From=" This snippet defines the animation for an assumed Image.TargetProperty="Opacity" Storyboard.TargetProperty="Opacity" F This snippet shows the alternate to increasing a value.8 shows the Opacity of the Ellipse changing from .260 WHERE AM I GOING? CHAPTER 9 Bringing it to life: Animation One way to predetermine where an animation is going is by setting the To property.9 XAML XAML demonstrating By property within a DoubleAnimation <DoubleAnimation Storyboard. Instea Snippet 9.8 XAML XAML demonstrating the To property within DoubleAnimation <DoubleAnimation Storyboard.TargetName="myImage" Storyboard.Henrik Thiesen <henrik.75 to 0 when the animation begi HOW AM I GOING TO GET THERE? The By property is a special shortcut that provides an alternate to the To property. Note that the By property itself is Licensed to SEB Link A/S .TargetName="myEllipse" Dura Snippet 9.10 XAML demonstrating From property within DoubleAnimation XAML <DoubleAnimation Storyboard.

Henrik Thiesen <henrik.3 How long should the animation run? As mentioned earlier.thiesen@seb.dk> . we have one final question to 9. so a number of valuable time-rel HOW LONG? The Duration property specifies how long it will take for a Timeline to complete a single e Table 9. each animation is a Timeline object.2.2 The effects of the SpeedRatio on a Timeline with a Duration of 10 seconds.1 illustrates that you have two different options when it comes to controlling the THROTTLING THE ANIMATION The SpeedRatio property represents the throttle for a Timeline. Licensed to SEB Link A/S . By default.1 Options for the Duration property Description Means that a Timeline will automati Property Automatic Forever Table 9. this double-pre Figure 9.Mastering the timeline 261 how long the animation should take to get to the destination.

Licensed to SEB Link A/S .3 The effects of the RepeatBehavior on a Timeline with a Duration of 10 seconds.Henrik Thiesen <henrik.dk> .262 PLAY IT AGAIN CHAPTER 9 Bringing it to life: Animation The RepeatBehavior property is an interesting animal that may act slightly different than y Figure 9.thiesen@seb.

11 Timeline with offset of 5 seconds XAML <DoubleAnimation Storyboard. But the beg FROM THE TOP The BeginTime property represents when to start playing a Timeline.dk> .TargetProperty="Opacity" F Licensed to SEB Link A/S .Henrik Thiesen <henrik. you may want to consid TURN IT AROUND The AutoReverse property enables you to automatically play a Timeline in reverse after it h HOW WILL IT END? When an animation reaches the end of a Timeline. it normally stays.thiesen@seb.Mastering the timeline 263 at times you may want a more cyclic animation. a Ti Stop You have two options: You can either stay at the end or reset to the beginning. For these situations. this proper Snippet 9.TargetName="myImage" Storyboard. or holds at the end.2 Value HoldEnd The available FillBehavior options Description When completed. In reality. bu Table 9.

A Storyboar 9.3.3 Storyboarding Every animation created within Silverlight must be defined within a Storyboard.thiesen@seb. This Storyboard element could have any Snippet 9.13 Syntax of Storyboard element with multiple animations <Storyboard x:Name="myStoryboard" Storyboard.dk> .1 Understanding the storyboard A Storyboard is an umbrella under which multiple animations can be defined to address a com Snippet 9.TargetName="myRectangle"> <DoubleAnimation x:N Licensed to SEB Link A/S .264 CHAPTER 9 Bringing it to life: Animation This snippet shows an Image that fades in over the course of one second.The common animations --> </Storyboard> This snippet shows the basic syntax of a Storyboard.12 Basic syntax of Storyboard element XAML XAML <Storyboard x:Name="myStoryboard"> <!-.Henrik Thiesen <henrik. Unlike the previou 9.

thiesen@seb. the Storyboard exposes two attached properties that can be used to se Snippet 9. This target is Licensed to SEB Link A/S . <Rectangle x:Name="myRectangle" Width="180" Height="120" Fill="Green" /> <Rectangle x:N This snippet defines the primary target of the Storyboard as myRectangle B.2 Hitting the target As mentioned earlier.Henrik Thiesen <henrik.Storyboarding From="Green" To="Blue" /> </Storyboard> .....dk> . <Rectangle x:Name="myRectangle" Width="180" Hei 265 This snippet shows a Storyboard that changes a Rectangle from green to blue as it fades int 9.3.TargetName=“myRectangle”> <ColorAnimation x:Na XAML B C D XAML E .14 Animation overriding target of its parent Storyboard <Storyboard x:Name=“myStoryboard” Storyboard.

..Henrik Thiesen <henrik.266 CHAPTER 9 Bringing it to life: Animation To target a property within an animation.thiesen@seb. <Rectangle x:Name="myRectangle" Width="120" Height="60" > <Rectangle.Fill> <LinearGradi D E Licensed to SEB Link A/S .TargetName="myRectangle"> <ColorAnimation Stor B XAML C .15 Using the daisy-chain syntax to change the individual colors of a LinearGradie <Storyboard x:Name="myStoryboard" Storyboard.dk> . As Snippet 9. you use the TargetProperty attached property.

.3 Methods associated with the Storyboard object Description Turns the hourglass to Method Begin(.Storyboarding 267 This snippet shows how to use the daisy-chain syntax to access the individual colors used w Figure 9.) Seek(..thiesen@seb. This ap 9....3..Henrik Thiesen <henrik.) Pause(.) Resume(.) Licensed to SEB Link A/S ...3 Controlling the Storyboard The Storyboard class exposes a number of valuable methods that empower you to programmatica Table 9..dk> ..4 The daisy-chaining syntax in action This figure shows the general syntax used for referencing daisy-chained properties.) Stop(.

an important part of intera Snippet 9.com/video2. MouseButtonEventArgs e) { myStoryboard e void myStoryboard1_Completed(object sender.268 CHAPTER 9 Bringing it to life: Animation the user control via interactive playback features.thiesen@seb.silverlightinaction.wmv B XAML XAML C D C# void myMediaElement_MouseLeftButtonUp(object sender. as well as on Licensed to SEB Link A/S . Either way. EventArgs e) { myStoryboard2.Henrik Thiesen <henrik.16 An animation that uses the playback methods and the Completed event <MediaElement x:Name="myMediaElement" Source="http://www.Begin(). } F This snippet shows how you can programmatically use both the Completed event.dk> .

17 Defining a Storyboard as a resource <Canvas x:Name="myCanvas"> <Canvas. myStoryboard. This event handler will then start the animation defined in d.thiesen@seb. The definition of t Snippet 9.Resources> <Storyboard x:Name="myStoryboard"> <DoubleAni b This snippet shows how easy it is to define a Storyboard as a resource.dk> .16 al 9. A resour Snippet 9.18 Starting a Storyboard from code-behind Storyboard myStoryboard = (Storyboard)(this.Begin() XAML c Licensed to SEB Link A/S . Snippet 9.FindName("myStoryboard")).Storyboarding 269 triggered f. These animations STORYBOARD AS A RESOURCE The first approach for organizing a Storyboard involves defining it as a resource.4 Being resourceful Storyboard elements enable you to create complex and intricate animations.3.Henrik Thiesen <henrik.

Insert Actions here --> </EventTr As this snippet shows. the RoutedEvent property uses a syntax that resembles elementTypeNam Snippet 9. An E Snippet 9.Insert Actions here --> < This snippet shows how the EventTrigger has been added to a Canvas. Significantly.20 Adding the EventTrigger to the collection of Triggers <Canvas.19 Defining an EventTrigger XAML XAML <EventTrigger RoutedEvent="Canvas.dk> .Loaded"> <!-.thiesen@seb.Triggers> <EventTrigger RoutedEvent="Canvas.Henrik Thiesen <henrik.Loaded"> <!-.270 CHAPTER 9 Bringing it to life: Animation This snippet illustrates how simple it is to programmatically start a Storyboard defined as STORYBOARD AS A TRIGGER The second approach for defining a Storyboard involves setting it as an event handler. this doe Licensed to SEB Link A/S .

thiesen@seb.dk> . you’l 9. until Silverlight matures. To put all the pieces together.Key framing 271 ing an EventTrigger. But. defining a Storyboard as a trigger wou Snippet 9. animators will often present a high-level overview o XAML Licensed to SEB Link A/S .21 Defining a Storyboard as an event trigger <Canvas Width="100" Height="100" Background="White"> <Canvas.4 Key framing In the realm of traditional animation.Triggers> <EventTrigger Routed This snippet shows a Storyboard defined as a trigger.Henrik Thiesen <henrik.

dk> . This example uses two key frame XAML Licensed to SEB Link A/S .Henrik Thiesen <henrik.5 A bouncing ball over some variable amount of time Snippet 9.22 Creating a bouncing ball using key frames <Canvas Width="640" Height="480" Background="White"> <Ellipse Width="50" Height="50" x:Name This snippet illustrates the general syntax of a KeyFrame.thiesen@seb.272 CHAPTER 9 Bringing it to life: Animation Figure 9.

The KeyFrame determines how to interpolate these values by referring to the Table 9.6 How linear interpolation is determined Licensed to SEB Link A/S .4 The key frame types available within Silverlight 2 Linear key frame types LinearC Discrete key frame types DiscreteColorKeyFrame DiscreteDoubleKeyFrame DiscreteObjectKeyFram LinearPointKeyFrame SplinePointKeyFrame Each type of key frame helps to address specific animation scenarios.4. or decelerat LINEAR INTERPOLATION Linear interpolation constructs the most direct transition between two key frames. The line Figure 9.Henrik Thiesen <henrik.1 Interpolation: It’s about acceleration An interpolation type gives you control over how an animation will accelerate. To understand when a 9.thiesen@seb.dk> .Key framing 273 each KeyFrame.

seamless transitions.274 CHAPTER 9 Bringing it to life: Animation The idea of using an animation that occurs at a constant.Henrik Thiesen <henrik.7 An example using spline interpolation for approximation Licensed to SEB Link A/S .dk> .thiesen@seb. predictable rate at first seems a SPLINE INTERPOLATION Splines are generally used to create smooth. These transitions occur Figure 9.

1.9 Sample time/value curves used by the KeySpline property Licensed to SEB Link A/S . These rifts se Figure 9.0.8 The relationship between time and value as used by the KeySpline property.0 Value Time <SplineDoubleKeyFrame x:Name="myKeyFrame"value="100" KeySpline="0.Henrik Thiesen <henrik.01.0.1.0.Key framing 275 1.0 0.0. the animation will DISCRETE INTERPOLATION Occasionally.0. In th more quickly. you may have to create an animation that jumps between values.thiesen@seb.0. Alternatively.dk> . if the x value is greater than the y value.0" KeyTime="00 Figure 9.

Page" xmlns="http://schemas.thiesen@seb.Henrik Thiesen <henrik.23 Using a TimeSpan value to specify the KeyTime. Each car represents the locatio Result XAML <UserControl x:Class="CarAnimation.microsoft.10 An example using discrete interpolation for approximation dom from dark holes.4.2 Timing is everything The KeyTime property of a KeyFrame represents the time at which the value specified within Snippet 9.dk> .276 CHAPTER 9 Bringing it to life: Animation Figure 9.com/wi Licensed to SEB Link A/S . This surprising effect can be effectively re-created using discrete in 9.

Triggers> 277 XAML B This snippet shows the typical approach for defining KeyFrame elements within an animation 9.dk> . you saw the details associated with animating elements within Silv Licensed to SEB Link A/S .Summary Width="400" Height="400"> <Canvas x:Name="LayoutRoot" Background="White"> <Canvas.Henrik Thiesen <henrik.5 Summary Throughout this chapter.thiesen@seb.

thiesen@seb.Henrik Thiesen <henrik.dk> . These featu 278 Licensed to SEB Link A/S .Giving it style This chapter covers ■ ■ ■ ■ Using application resources Control styling Building control templates The VisualStateManag Chapter 9 described the powerful animation features available in Silverlight 2.

1.1 Being resourceful In general. This practice make 10.dk> .Being resourceful 279 10.1 Declarative resources Declarative resources are items intended to be shared across multiple elements.thiesen@seb.Resources> <LinearGradientBrush x:Key="myGradientBrush" Sta B XAML C This snippet shows a basic declarative resource in the form of a LinearGradientBrush B. Thi Licensed to SEB Link A/S . it’s a good idea to create reusable items whenever possible.1 The basic syntax and usage of a resource Result <StackPanel> <StackPanel. They can be Snippet 10.Henrik Thiesen <henrik.

Resources> <SolidColorBrush x:Key="theSolidC This snippet shows how to define a resource at design time and runtime.280 CHAPTER 10 DEFINING DECLARATIVE RESOURCES Giving it style Resources must be defined within an appropriately named collection called Resources. it can be referenced at design time through the StaticRe Licensed to SEB Link A/S . Both approaches req REFERENCING DECLARATIVE RESOURCES AT DESIGN TIME After a resource has been defined.dk> .thiesen@seb.Henrik Thiesen <henrik. This c Snippet 10.2 The same SolidColorBrush defined as a resource at design time and runtime <StackPanel x:Name="myStackPanel"> <StackPanel.

Being resourceful 281 Snippet 10.4 object resource = myStackPanel. Notice the use of the StaticResource ke XAML XAML C# <TextBlock x:Name="myTextBlock" Text="Hello.dk> . Once it’s Licensed to SEB Link A/S . World" Fore This snippet shows a valid syntactical use of a resource.thiesen@seb.Resources["theSolidColorBrush"]. If you attempt to run this snippe USING DECLARATIVE RESOURCES AT RUNTIME Referencing resources at design time is useful for setting up the initial state of an appli Snippet 10. The StaticResource Snippet 10.3 Referencing a resource at design time. if (resource != null) { Sol This snippet retrieves the SolidColorBrush defined as a resource in snippet 10.4 An invalid use of a resource at design time <StackPanel x:Name="myStackPanel"> <TextBlock x:Name="myTextBlock" Text="Hello.4.Henrik Thiesen <henrik. World" Foreground="{StaticResourc This snippet shows the basic syntax for using a resource at design time.5 Retrieving the SolidColorBrush defined in snippet 10.

282 CHAPTER 10 Giving it style interesting. the TextBlock in snippet 10. change occurs at runtime.2 Accessing loose resources In addition to using resources defined within your XAML.thiesen@seb. When this code is executed.dk> .1.Henrik Thiesen <henrik. Silverlight enables you to access REFERENCING RELATIVE LOOSE RESOURCES Silverlight allows you to access loose resources relative to the site of origin—the locatio Licensed to SEB Link A/S .

silverlightinaction.thiesen@seb.Being resourceful 283 directory.8 An absolute Uri accessing a loose resource <Image x:Name= "myImage" Source="http://www.Henrik Thiesen <henrik.dk> . Thi Snippet 10.png" /> This snippet accesses a resource in the same directory as MySilverlightApplication.com/image03.7 A Uri accessing a relative loose resource in a subdirectory <Image x:Name="myImage" Source="directory/image02.xap. so this directory can be considered the site of origin.png" /> This snippet shows how to access a loose resource via an absolute Uri. demonstrating that RETRIEVING LOOSE RESOURCES WITH AN ABSOLUTE URI Silverlight gives you the flexibility to access loose resources via an absolute Uri. As you may have expe Licensed to SEB Link A/S . This g Snippet 10.png" /> This snippet shows how to reference a loose resource in a subdirectory.6 A Uri accessing a relative loose resource XAML XAML XAML <Image x:Name="myImage" Source="image01. If you want to access im Snippet 10.

9 An absolute Uri accessing a loose resource in a subdirectory XAML XAML <Image x:Name="myImage" Source="http://www. The leading Licensed to SEB Link A/S . This Uri po 10.png" /> This snippet shows the syntax used to reference a content file at design time.xap file and deployed alongside a Silverlight app Snippet 10.silverlightinaction.thiesen@seb.Henrik Thiesen <henrik. This path is based on the <Image x:Name="myImage" Source="/images/image.dk> .com/resources/imag This snippet uses an absolute Uri to access a loose resource in a subdirectory.1.3 Bundling resources The third kind of resource used in Silverlight is referred to as a bundled resource.10 Referencing a relative content file at design time.284 CHAPTER 10 Giving it style Snippet 10. A bund USING CONTENT FILES A content file is one that is added to a .

When it’s compiled. which may be either an a Licensed to SEB Link A/S .Henrik Thiesen <henrik. Sometimes.Being resourceful 285 Figure 10.2 How to define a file as a content file.dk> .thiesen@seb. a content file is a a Silverlight application because it makes things more easily accessible. you ma USING EMBEDDED FILES An embedded file is a file embedded within a Silverlight assembly.

The design-time implementation relies Snippet 10.2 Giving your elements style As you saw in section 10.12 The brute-force approach to defining the visual properties of multiple elemen Licensed to SEB Link A/S . This resource is represe 10.RowDefinitions> <RowDefinition></RowDefinition> <Row This snippet shows how to retrieve the resource from the assembly.Henrik Thiesen <henrik.png at runtime C# Result <Grid x:Name="myGrid"> <Grid.1.11 Referencing an assumed embedded file called embedded.thiesen@seb. Thes Snippet 10. resources are the nonexecutable parts of your application.286 CHAPTER 10 Giving it style This template can be used at design time or runtime.dk> .

Thi SETTING SIMPLE PROPERTY VALUES A simple property is a property that can be set at design time with a primitively typed val Licensed to SEB Link A/S .1" StartPoint="0.Giving your elements style <TextBox.5.Henrik Thiesen <henrik. you must simply set the Style property.Background> <LinearGradientBrush EndPoint="0.1 Defining the look To define the look of an element using a Style.5.0"> <GradientSto 287 This snippet shows the brute-force approach to defining the visual properties of multiple e 10.2.thiesen@seb.dk> .

T Result <TextBox x:Name="myTextBox"> <TextBox.Style> <Style TargetType="TextBox"> <Setter Pr B XAML C This snippet shows how to define a Style B that uses five simple properties C. In general.thiesen@seb. The text in the TextBox is entered at runtime.13 A basic Style definition.Henrik Thiesen <henrik. Result <TextBox x:Name="myTextBox"> <TextBox. each of whic SETTING COMPLEX PROPERTY VALUES A complex property is a property whose value is a general-purpose object.14 An example of using a complex property value as part of a Style definition.dk> .288 CHAPTER 10 Giving it style of values can be used at design time to set the property values for properties like FontSiz Snippet 10. these Snippet 10.Style> <Style TargetType="TextBox"> <Setter Pr Licensed to SEB Link A/S .

it can’t be set again.15 Defining the TargetType of a Style <Grid x:Name="myGrid" Background="White"> <Grid.Resources> <Style x:Key="textStyle" TargetT B Licensed to SEB Link A/S . once a Style is set. style definitions are made up of two parts.Henrik Thiesen <henrik.2 Targeting style definitions In CSS.2.thiesen@seb.Giving your elements style <Setter Property="FontSize" Value="12"></Setter> <Setter Property="FontWeight" Value="Bold" 289 XAML B This snippet shows how to define a more complex property as part of a Style B. In Silverlight. One part represents the name of the sty NOTE Style definitions are static.dk> . T Snippet 10. There aren’t 10.

The Style in this case is configured to b 10.thiesen@seb.3 Creating templates The styling features shown in section 10.Henrik Thiesen <henrik. Licensed to SEB Link A/S .290 CHAPTER 10 Giving it style XAML <Setter Property="FontFamily" Value="Verdana" /> <Setter Property="FontSize" Value="12" /> This snippet shows a Style defined as a resource.2 are a welcome addition to the Silverlight world.dk> .

Creating templates 291

10.3.1 Building a control template When you build a control template, it will ultimately be used with a Control. Every Control Snippet 10.16 Changing the look of a Button through a Template Result <Button x:Name="myButton" Content="Hello"> <Button.Template> <ControlTemplate> <Elli B C

This snippet shows a basic ControlTemplate C. This ControlTemplate is associated with a But XAML Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

292 CHAPTER 10 Giving it style

arranged. But first, you’ll see how to use properties that are part of the target control i CONSIDERING CONTROL PROPERTIES

Ultimately, the purpose of a ControlTemplate is to define the appearance of a Control. This Snippet 10.17 Using a TemplateBinding to use the target elements properties Result <Button x:Name="myButton" Content="Hello" Height="45" Width="45"> <Button.Template> B

This snippet shows the basic syntax of a TemplateBinding B. This syntax mimics the data-bin DISPLAYING THE CONTENT

You may have noticed that the Content of the Button elements in the past two snippets hasn’ Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Creating templates 293 Snippet 10.18 Using a ContentPresenter to display the Content of a ContentControl Result <Button x:Name="myButton" Content="Hello" Height="20" Width="60"> <Button.Template>

This snippet shows the general usage of a ContentPresenter. As you can see, this object is Snippet 10.19 Using an ItemsPresenter to display the Items of an ItemsControl Result <ListBox x:Name="myListBox"> <ListBox.Template> <ControlTemplate> <Border CornerRadi XAML B XAML

<ListBox.Items> <ListBoxItem><TextBlock>Item 1</TextBlock></ListBoxItem> <ListBoxItem><Text

This snippet shows a ListBox with a ControlTemplate applied to it. The Items of that ListBo Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

294 CHAPTER 10 CONTROLLING ITEM ARRANGEMENT Giving it style

The Items of an ItemsControl control are arranged according to the ItemsPanel property. Thi Snippet 10.20 Declaring the ItemsPanel to arrange the Items of an ItemsControl Result <ListBox x:Name="myListBox"> <ListBox.Template> <ControlTemplate> <Border CornerRadi

This snippet uses a Horizontal StackPanel as the ItemsPanel to arrange the Items in the Lis Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Dealing with visual states 295

ItemsControl, you may need to use an ItemsPresenter to show the Items. These Items can be r makes it easy to create reusable templates.

10.3.2 Creating reusable templates Creating individual templates can be useful when you want to give individualized attention Snippet 10.21 Using a ControlTemplate within a Style Result <StackPanel x:Name="LayoutRoot" Background="White" Margin="10" Width="170"> <StackP B XAML C

<Button x:Name="myButton1" Height="30" Width="30" Style="{StaticResource buttonStyle}" /> <

This snippet shows a ControlTemplate C defined within a Style B. This ControlTemplate is th

10.4 Dealing with visual states Templates give you the flexibility to completely dictate how a Control looks, but the templ Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

296 CHAPTER 10 Giving it style most controls have multiple states. For instance, a Button can be in a pressed or disabled

10.4.1 Understanding the components The VisualStateManager relies on a variety of components to do its job. These components ma STATES

A state is used to reflect a particular aspect of a Control. For instance, the Button has o Normal MouseOver Pressed Table 10.1 Several states of a Button. Each state has a slightly d

This table shows three of the states exposed by the Button class. In reality, the Button cl Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

Dealing with visual states 297 State Disabled MouseOver Normal Pressed Focused Unfocused

GroupName CommonStates CommonStates CommonStates CommonStates FocusStates FocusStates Table

state as well as a Pressed state because the Pressed state is in a different group than the TRANSITIONS A transition defines the way a Control looks as it changes from one state to another. This PARTS

A part represents a specific element within a ControlTemplate. A part is generally used whe Figure 10.3 The parts of a Slider Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

298 CHAPTER 10 Giving it style

10.5 Leveraging the VisualStateManager The VisualStateManager is used by a ControlTemplate to manage the change between states. Th CREATING STATE-BASED EFFECTS

A state-based effect is a transition that occurs at the moment a Control enters a VisualSta Snippet 10.22 Creating a Button that enlarges when a user hovers over it <Button x:Name="myButton" Width="75" Height="75" Content="Push Me"> <Button.Template> <Cont XAML VerticalAlignment="Center"

<ContentPresenter HorizontalAlignment="Center" /> <VisualStateManager.VisualStateGroups> <V B Licensed to SEB Link A/S - Henrik Thiesen <henrik.thiesen@seb.dk>

TargetName="myTransform" Storyboard.dk> .Henrik Thiesen <henrik. the VisualStateManager empowers you to define a tra Snippet 10. it <Button x:Name="myButton" Width="75" Height="75" Content="Push Me"> <Button.thiesen@seb.Leveraging the VisualStateManager Storyboard.23 Creating a Button that transitions when a user hovers.TargetProperty="ScaleX" /> <DoubleAnimation 299 B This snippet defines an effect that occurs when a user triggers the MouseOver VisualState f DEFINE TRANSITIONING EFFECTS In addition to state-based transitions.Template> <Cont XAML XAML Licensed to SEB Link A/S . or leaves.

5" CenterY="0.Henrik Thiesen <henrik.141"/> <SkewTransform CenterX="0.VisualStateGroups> <V B c XAML d e Licensed to SEB Link A/S .075" ScaleY="1.300 CHAPTER 10 Giving it style ScaleX="1.5"/> <RotateTransfo VerticalAlignment="Center" <ContentPresenter HorizontalAlignment="Center" /> <VisualStateManager.thiesen@seb.dk> .

dk> . This empowers you to d Snippet 10.thiesen@seb.Sharing your effects Storyboard. The first VisualTransi 10.24 Creating a Button that enlarges when a user hovers over it <Grid x:Name="LayoutRoot" Background="White"> <Grid.TargetProperty="ScaleY" /> </Storyboard> </V 301 e This snippet shows the definitions of two VisualTransition elements.Resources> <Style x:Key="buttonStyle" T Licensed to SEB Link A/S .TargetName="myTransform" Storyboard.Henrik Thiesen <henrik.6 Sharing your effects Because the effects you create with the VisualTransition and VisualState elements are part XAML XAML Share your effects throughout your application The Application class exposes a ResourceDictionary called Resources.

thiesen@seb.VisualStateGroups> <V Licensed to SEB Link A/S .Henrik Thiesen <henrik..dk> .Value> <ControlTemplate TargetType="Button"> <Grid RenderTransformOrigin=".302 CHAPTER 10 Giving it style <Setter.5"> < XAML VerticalAlignment="Center" <ContentPresenter HorizontalAlignment="Center" /> <VisualStateManager.5.

Summary Storyboard. This control model empo XAML Licensed to SEB Link A/S .TargetProperty="ScaleX" /> <DoubleAnimation 303 This snippet shows a Button ControlTemplate defined as a Style.dk> . This ControlTemplate uses t 10.thiesen@seb.Henrik Thiesen <henrik.7 Summary This chapter showed the flexibility of Silverlight’s control model.TargetName="myTransform" Storyboard.

304 CHAPTER 10 Giving it style The features displayed in this chapter are powerful enhancements that you will generally im Licensed to SEB Link A/S .Henrik Thiesen <henrik.dk> .thiesen@seb.

Enhancing the experience This chapter covers ■ ■ ■ ■ Storing data in isolated storage Asynchronously running tasks Dynamically retrieving conten Throughout this book. you’ve witnessed how to use Silverlight to create RIAs.dk> .Henrik Thiesen <henrik.thiesen@seb. which clearly 305 Licensed to SEB Link A/S .

so it has the lowest of security privileges to ensu NOTE The GetUserStoreForSite method doesn’t exist in the full .NET framework.1 IsolatedStorageFile: The virtual filesystem The IsolatedStorageFile class represents a virtual filesystem that a Silverlight applicatio Licensed to SEB Link A/S . an example of retrieving an IsolatedStorageFile is shown in snippet 11. Once you’ve retrieved a 11.306 CHAPTER 11 Enhancing the experience 11. Snippet 11.dk> .1 Storing data in isolated storage Silverlight is a browser-based plug-in.1.1 Retrieving the isolated storage for a user C# IsolatedStorageFile isoFile = IsolatedStorageFile.thiesen@seb. You should conside Either way.1.GetUserStoreForApplication(). This code gives you access to the isolated storage area for a user.Henrik Thiesen <henrik.

string[] noDirFound = isoFil As this snippet shows.thiesen@seb.dk> .2 Retrieving explicitly named files and directories string[] directory1 = isoFile. you can easily retrieve both directory and file names using an absol Licensed to SEB Link A/S .Henrik Thiesen <henrik.GetDirectoryNames("Directory1").Storing data in isolated storage 307 The IsolatedStorageFile object represents a specific partition within the isolated storage LISTING THE CONTENTS OF THE VIRTUAL FILESYSTEM The IsolatedStorageFile class provides two methods that enable you to retrieve the items wi Snippet 11.

txt").Henrik Thiesen <henrik. you must explicitly provide the absolute path to the file you wish t Licensed to SEB Link A/S .4 Removing items from the isolated storage area C# soFile.txt").1 C# string[] results1 = string[] results2 = isoFile.Get This snippet illustrates the flexibility associated with using the * wildcard character. isoFile. This table demonstrates how the ? wildcard works.308 CHAPTER 11 Enhancing the experience Snippet 11. This character.1 Using the ? wildcard character in relation to figure 11. Al Table 11.thiesen@seb.GetFileNames("te?tfile*"). in coordination with the REMOVING ITEMS FROM ISOLATED STORAGE The IsolatedStorageFile class exposes two utility methods that empower you to remove items Snippet 11.DeleteFile("Directory1/file1.3 Using the * wildcard character string[] string[] string[] string[] results1 results2 results3 results4 = = = = isoFile.dk> .DeleteFile("testfile1. As this snippet shows.

6 Creating subdirectories within the isolated storage area C# isoFile.5 Creating a directory within the isolated storage area C# isoFile.CreateDirectory("Directory1/SubDirectory1").Storing data in isolated storage CREATING DIRECTORIES WITHIN ISOLATED STORAGE 309 The IsolatedStorageFile class exposes a method called CreateDirectory that enables you to c Snippet 11.thiesen@seb. In addition to creating directories at the root of the isolated storage area.dk> .CreateDirectory("Directory1 B c The first line of code B is pretty simple.microsoft.7 Creating a file quota bar associated with the user’s isolated storage area Result <UserControl x:Class="Chapter11. The second line of code shows an additional feat CHECKING THE AVAILABLE SPACE The IsolatedStorageFile class exposes two read-only properties that inform you of an isolat Snippet 11.Snippet07" xmlns="http://schemas. the CreateDir Snippet 11.com/winfx Licensed to SEB Link A/S .Henrik Thiesen <henrik. isoFile.CreateDirectory("Directory1").

Henrik Thiesen <henrik.Top="5" RadiusX="5" RadiusY="5" StrokeThickness=" C# XAML B This snippet shows one way you can put the AvailableFreeSpace and Quota properties to use.thiesen@seb.Left="1" Canvas.310 CHAPTER 11 Enhancing the experience Stroke="#FF000000" Canvas. This req Licensed to SEB Link A/S .dk> . REQUESTING MORE SPACE The IsolatedStorageFile class empowers you to ask the user for more storage space.

GetUserStoreForApplication().Henrik Thiesen <henrik. more space for an application. long This snippet shows how to request. You also hav 11.dk> .1. This specific dialog box asks the user Result IsolatedStorageFile isoFile = IsolatedStorageFile.8 Requesting more isolated storage space.thiesen@seb. from a user.2 Reading and writing files: The isolated storage way Files stored within the isolated storage area can be created and retrieved through a file s C# Licensed to SEB Link A/S .Storing data in isolated storage 311 Snippet 11.

2 The ways to open a file Description Opens an existing file and prepares to add c FileMode Append Create CreateNew Licensed to SEB Link A/S . This process hin Snippet 11.GetUserStoreForApplication()) { us B C C# D This snippet shows how easily you can write a text file into the isolated storage area.312 CHAPTER 11 Enhancing the experience The IsolatedStorageFileStream object provides in-memory access to a file stored within the ISOLATED FILE CREATION Creating a file within a user’s isolated storage area is a simple process.9 Creating a file within a user’s isolated storage area using (IsolatedStorageFile isoFile = IsolatedStorageFile.Henrik Thiesen <henrik.dk> .thiesen@seb. The Table 11.

dk> . If the file doesn’t exist.GetUserStoreForApplication()) { us B C C# D As this snippet shows. reading a file is almost identical to creating a file. The contents of the file using (IsolatedStorageFile isoFile = IsolatedStorageFile. a new one will be created with the gi Truncate The FileMode options shown in this table cover a wide variety of file operations.10 Reading a file from a user’s isolated storage area. The first ste Licensed to SEB Link A/S .2 The ways to open a file (continued) Description Attempts to open a file with the 313 FileMode Open OpenOrCreate Opens a file if it exists.Henrik Thiesen <henrik.thiesen@seb.Storing data in isolated storage Table 11. These val READING AN ISOLATED FILE The process of reading a file from a user’s isolated storage area is similar to writing to Snippet 11.

At this point.Henrik Thiesen <henrik.3 Administering the isolated storage Administering an isolated storage area involves interacting with the physical filesystem. Each unique Silverlight a 11.314 CHAPTER 11 Enhancing the experience 11. we gave a quick overview of the features of XAML. I hope you h Licensed to SEB Link A/S .3 The base location of the isolated storage area on each operating system supporte This table shows the base location for the isolated storage area.thiesen@seb.2 Using XAML at runtime In chapter 1.dk> . T Table 11.1.

dk> .thiesen@seb.microsoft.Henrik Thiesen <henrik. Then you can inser Snippet 11.12 Loading XAML with nested elements at runtime string xaml = "<Grid xmlns=\"http://schemas.com/winfx/2006/xaml/presentatio C# B C D This snippet creates a Rectangle from a string of XAML B.Using XAML at runtime 315 method takes a string of XAML and converts it to the appropriate object.microsoft.com/winfx/2006/xaml/presentation\"> This snippet adds a Grid to an assumed Canvas.11 Loading some XAML at runtime string xaml = "<Rectangle xmlns=\"http://schemas. This Grid contains a variety of other valuab C# Licensed to SEB Link A/S . The Rectangle will be created by Snippet 11.

you can easily create the look of a ProgressBar using XAML and/or Bl 11.ComponentModel namespace provides a class called BackgroundWorker that can be us Snippet 11.1 Doing the work To do the work.Henrik Thiesen <henrik.316 CHAPTER 11 Enhancing the experience data source. you have to create an instance of the BackgroundWorker class.13 The XAML for the progress bar. Unfortunately. calling a web service can be a time-consuming process.3 BackgroundWorker The System. The figure shown is simply for illustration.3.dk> . After this is XAML Licensed to SEB Link A/S .thiesen@seb. T Result <ProgressBar x:Name="myProgressBar" Height="30" Width="250" Background="White" Borde As this snippet shows. which ca 11.

RoutedEventArgs e) { InitializeComponent().thiesen@seb. backgrou C C# D E In this snippet.Henrik Thiesen <henrik.dk> .14 Implementing the DoWork event private BackgroundWorker backgroundWorker = null.2 Updating the UI The BackgroundWorker class exposes two events that can be used to update the UI.BackgroundWorker 317 Snippet 11.3. These two Licensed to SEB Link A/S . you’ll notice that a BackgroundWorker variable is defined at the classscop 11. B public void Page_Loaded(object sender.

The Snippet 11. i D private void backgroundWorker_ProgressChanged(object sender.thiesen@seb. backgroundWorke private void backgroundWorker_DoWork(object sender.dk> .15 Reporting progress changes from the BackgroundWorker private BackgroundWorker backgroundWorker = null.Henrik Thiesen <henrik. DoWorkEventArgs e) { for (int i = 1. Ro B C backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork). you c SHOWING PROGRESS CHANGES Sending progress updates to the UI from a BackgroundWorker involves three basic steps. The first Licensed to SEB Link A/S . But. public void Page_Loaded(object sender.318 CHAPTER 11 Enhancing the experience cause your UI to hang and create less-than-desirable experiences for your users. ProgressChangedEventArgs e) { C This snippet shows how to report the progress of a task from a BackgroundWorker.

DoWork += new DoWorkEventHandler(backgroundWorker_DoWork).Sleep(25).thiesen@seb. To cancel a Snippet 11. backgroundWorke C private void backgroundWorker_DoWork(object sender.Henrik Thiesen <henrik. Licensed to SEB Link A/S .dk> . public void Page_Loaded(object o.16 Canceling a BackgroundWorker when a user selects the Escape key private BackgroundWorker backgroundWorker = null. Thread. EventAr B C# } backgroundWorker.BackgroundWorker 319 As you can see. ENABLING TASK CANCELLATION Canceling a BackgroundWorker task is similar to handling a change in progress. DoWorkEventArgs e) { for (int i = 1.ReportProgress(i). i D backgroundWorker. this method is periodically called from within the DoWork event handler D.

This co ALL DONE The RunWorkerCompleted event occurs when a BackgroundWorker is finished with the task defin ■ ■ ■ The DoWork event handler was canceled. C# public void Page_Loaded(object o. you may want to provide a specific typ Snippet 11.thiesen@seb.dk> . The DoWork event handler successfully completed the Depending on which of these situations has occurred.17 Handling the completion of the background task private BackgroundWorker backgroundWorker = null. CHAPTER 11 Enhancing the experience This snippet shows a BackgroundWorker that runs until a user clicks the Escape key.Henrik Thiesen <henrik. Even Licensed to SEB Link A/S ..320 } C# } ..

WorkerReportsProgress = true.thiesen@seb.dk> . b 321 B C# C In this snippet.Henrik Thiesen <henrik. you define the event handler C for the RunWorkerCompleted event B.Retrieving content on demand backgroundWorker = new BackgroundWorker().4 Retrieving content on demand One of the great new features within the world of entertainment has been the addition of on Licensed to SEB Link A/S . backgroundWorker. Althoug 11.

This content Snippet 11.silverlightinaction. this content ca 11.322 CHAPTER 11 Enhancing the experience To retrieve items on demand. met REQUESTING STRING CONTENT The DownloadStringAsync method can be used to download string-related content.4. Sometimes. The first step REQUESTING BINARY DATA The OpenReadAsync method can be used to request binary content. but different.thiesen@seb.19 Asynchronously requesting binary content using the WebClient class public void RequestStreamContent() { Uri uri = new Uri("http://silverlightinaction.com/vide Licensed to SEB Link A/S .18 Requesting some string content through the WebClient object public void RequestStringContent() { Uri uri = new Uri("http://www.dk> .com/ C# B C This snippet shows how to request string-based content using the WebClient.1 Requesting content The WebClient class empowers you to request content through two similar. you must first request the content.Henrik Thiesen <henrik. This kind of content includ Snippet 11.

Henrik Thiesen <henrik. webClient.20 Responding to the DownloadProgressChanged event. you need to know when the download has completed. 323 C# B } This snippet shows how to request binary content using the WebClient class.OpenReadAsync(uri). W MONITORING THE PROGRESS The DownloadProgressChanged event empowers you to keep track of the advancement of a downlo Snippet 11. This event handler displays void webClient_DownloadProgressChanged(object sender.Text = sb. This process cl 11. This even Licensed to SEB Link A/S . DownloadProgressChangedEventArgs e) { C# B C myTextBlock.thiesen@seb.2 Managing larger download requests After a download request has been sent.ToString(). } This snippet demonstrates an event handler for the DownloadProgressChanged event.Retrieving content on demand WebClient webClient = new WebClient().dk> .4.

21 Canceling a download request.dk> . This snippet assumes a pretend Cancel button tr WebClient webClient = new WebClient(). you can see how many bytes CANCELING THE REQUEST Providing a user with information about the overall progress of a download can remove the p Snippet 11. Rou B C D This snippet shows an event handler for an imaginary Cancel button B.thiesen@seb.324 CHAPTER 11 Enhancing the experience of bytes of the requested content. As this content is retrieved. protected void cancelButton_Click(object sender. This event handler ca Licensed to SEB Link A/S .Henrik Thiesen <henrik.

Henrik Thiesen <henrik.22 This snippet uses a WebClient to call a JSON web service.Retrieving content on demand 325 11. This is impor Snippet 11.3 Loading the content When we discussed the process of requesting content in 11. DownloadStringCompletedEventArgs e) C D E Licensed to SEB Link A/S .geonames.org/findNearByWe C# B } void webClient_DownloadStringCompleted(object sender.4.1.dk> . you learned that you have tw LOADING STRING CONTENT Loading string content is an important task in the world of the mashable web.4. This web service re private void RequestContent() { Uri address = new Uri( "http://ws.thiesen@seb.

326 CHAPTER 11 Enhancing the experience This snippet uses a WebClient to call a web service that returns data in JSON.23 Loading media content that has been downloaded on demand private void RequestContent() { Uri address = new Uri("http://www. OpenReadCompletedEventArgs e) { myMediaEl E F This snippet loads a video.silverlightinaction.thiesen@seb. This met Licensed to SEB Link A/S .dk> . This web ser LOADING MEDIA CONTENT As you saw in chapter 7. when the RequestContent method is called B. on demand. media is an important part of the modern web. This important piece Snippet 11.Henrik Thiesen <henrik.com/v B C# C D } void webClient_OpenReadCompleted(object sender.

24 Loading media content that has been downloaded on demand.silverlightinaction.thiesen@seb. which beco LOADING FONTS Dynamically loading fonts on demand can add a significant amount of value within the realm Snippet 11.com/s C# B void webClient_OpenReadCompleted(object sender.Henrik Thiesen <henrik.dk> . Note that the somef private void RequestContent() { Uri address = new Uri("http://www. The first step in 1 The content is downloaded asynchronously if it hasn’t been previously requested. This method asynchronously downloads1 the requested video as a Stream.Retrieving content on demand 327 method D. When conte Licensed to SEB Link A/S . then uses it with a TextBlock. OpenReadCompletedEventArgs e) { FontSource D C This snippet dynamically retrieves a font.

328 CHAPTER 11 Enhancing the experience because a font is generally stored as a binary file. OpenReadCompletedEventArgs e) { Uri part C D E BitmapImage image = new BitmapImage(). The contents of this file are download LOADING COMPRESSED PACKAGES Compressed packages are useful for grouping multiple files in an easily transportable forma Snippet 11.thiesen@seb.com/f B C# } void webClient_OpenReadCompleted(object sender. Licensed to SEB Link A/S .Henrik Thiesen <henrik.25 Loading an image from a compressed package that was retrieved on demand private void RequestContent() { Uri address = new Uri("http://www.dk> .silverlightinaction.

dk> . which repr Once this process is completed.SetSource(imageStream.thiesen@seb. } 329 This snippet demonstrates how to extract a file out of a dynamically downloaded package.Stream). you’re free to use the content as needed. Convert the downloaded Stream. Th 1 2 C# 3 Retrieve the part to extract as a relative Uri C. This highlevel de Licensed to SEB Link A/S .Retrieving content on demand image.Henrik Thiesen <henrik. myImage.Source = image.

An applicat Licensed to SEB Link A/S . it will be returned in the form of a StreamResourceInfo These three steps empower you to easily load groupings of files on demand. an application module.CreateInstance("MyClassLibrary. Generally these LOADING APPLICATION MODULES Splitting an application into multiple application modules can make it significantly more m Snippet 11.Henrik Thiesen <henrik. and use. OpenReadCompletedEventArgs e) { Assemb C D object myClass = assembly.26 Dynamically retrieving an application module private void RequestContent() { Uri address = new Uri("http://www.MyClass").330 CHAPTER 11 Enhancing the experience Exception.silverlightinaction. If the file does exist. object result = myClass E This snippet shows how to dynamically download.dk> .thiesen@seb.com/M B } C# void webClient_OpenReadCompleted(object sender.

Henrik Thiesen <henrik.Canc B This snippet demonstrates how to check if a download was successful.27 Ensuring that a download was successful void webClient_OpenReadCompleted(object sender. This specific example C# C Licensed to SEB Link A/S . When this method has completed. the requested class library will be accessible through t OpenReadAsync DEALING WITH TERMINATION On-demand download requests may be stopped either intentionally or unintentionally.thiesen@seb. OpenReadCompletedEventArgs e) { if ((e. An inte Snippet 11.Retrieving content on demand 331 B.dk> .

This appro Table 11. IronPython.thiesen@seb.5 The Dynamic Language Runtime (DLR) DLR enables on-the-fly compilation and execution of a number of scripting languages including JScript. and IronRuby.5. If so 11.dk> .332 CHAPTER 11 Enhancing the experience The Cancelled property is a bool that lets you know if a download request was halted.4 An example of how dynamic typing can be used C# (Statically typed language) int Licensed to SEB Link A/S . Each of these language implementations runs on 11.Henrik Thiesen <henrik.1 Dynamic typing Dynamic typing means that type checking is performed when your code is executed.

dk> .5 Duck typing in action. C# (Statically typed language) public class Bird { public Licensed to SEB Link A/S .thiesen@seb.The Dynamic Language Runtime (DLR) 333 This table shows a small example that demonstrates the typing behavior difference between s ADVANTAGES OF DYNAMIC TYPING Dynamically typed languages in the DLR provide several advantages when compared to their st Table 11.Henrik Thiesen <henrik.

To get the code to Licensed to SEB Link A/S .28 The complete class library in C# public interface IFlyable { void Fly(TextBlock textBlock).dk> .6 Making the objects fly when a button is clicked. The C# version references an in approach. consider asking a flying object to fly once a button is clicked.334 CHAPTER 11 Enhancing the experience Table 11.thiesen@seb. } public class Bird : IFlyable { B C C# C This snippet shows the completed reworking of the flying object library. T Snippet 11.Henrik Thiesen <henrik. To illustrate.

To put a frame a Licensed to SEB Link A/S .dk> .The Dynamic Language Runtime (DLR) DISADVANTAGES OF DYNAMIC TYPING 335 Dynamically typed languages have several drawbacks compared to their statically typed sibli Table 11.Henrik Thiesen <henrik. the method signatures in this table seem fairly easy to understand. dynamic languages expose another interesting feature known a ADVANTAGES OF METAPROGRAMMING The idea of writing software that writes software can be quite compelling.5.2 Metaprogramming In addition to dynamic typing. but if 11.7 Method signature comparison between C# and IronPython C# (Statically Typed Langu At first glance.thiesen@seb.

336 CHAPTER 11 Enhancing the experience This figure shows the basic workflow of writing an application.dk> . You’ve personally experienc DISADVANTAGES OF METAPROGRAMMING Metaprogramming is somewhat like an extremely high-powered chainsaw. It can be an incredibl Licensed to SEB Link A/S .Henrik Thiesen <henrik.thiesen@seb.

Summary 337 fied by learning more about the DLR. there are a 11.Henrik Thiesen <henrik.6 Summary Throughout this chapter. we’ve explored a number of items that can enrich a user’s experien Licensed to SEB Link A/S .thiesen@seb. If you’d like to learn more about the DLR.dk> .

Henrik Thiesen <henrik. It’s been a 338 Licensed to SEB Link A/S .dk> .Share the light: Distribution and deployment This chapter covers ■ ■ ■ ■ Creating user controls Navigating between pages Enhancing the startup experience Hosting wi Throughout this book you’ve seen how you can use Silverlight to ignite the web.thiesen@seb.

1 Creating a user control Because Silverlight is still in its infancy.1.1.dk> . there may be times when none of the controls p 1 2 3 Defining the appearance of the control Defining the behavior of the control Calling the con This three-step process forms the ABCs of user-control development (Appearance.thiesen@seb.1 Defining the appearance Defining the appearance of a UserControl involves creating the XAML for the user interface.Henrik Thiesen <henrik. A user control can be used as a pa 12. a 12. Licensed to SEB Link A/S . Behavior.Creating a user control 339 creating a user control will be covered in section 12.

1 The user interface for the LockableTextBox UserControl <UserControl x:Class="MyClassLibrary.LockableTextBox" xmlns="http://schemas.microsoft.340 CHAPTER 12 Share the light: Distribution and deployment Snippet 12.com/w XAML D B C This snippet shows the XAML that makes up the default appearance of the LockableTextBox.dk> .Henrik Thiesen <henrik.1. This be Snippet 12.2 Defining the behavior The functionality of a reusable control is also known as the behavior of a control. Th 12. MouseButtonEventArgs e) { IsLocked = C D Licensed to SEB Link A/S .thiesen@seb.2 The LockableTextBox class definition public partial class LockableTextBox : UserControl { public LockableTextBox() { InitializeC B C# private void myImage_MouseLeftButtonUp(object sender.

png" 341 D E C# public static readonly DependencyProperty IsLockedProperty = DependencyProperty.silverlightinaction.Creating a user control { myImage.Source = new BitmapImage( new Uri("http://www.dk> .Register( " F This class definition for a LockableTextBox uses a constructor to serve as the primer for t Licensed to SEB Link A/S .thiesen@seb.com/locked.Henrik Thiesen <henrik.

342 CHAPTER 12 Share the light: Distribution and deployment a DependencyProperty.1 Comparing a traditional property definition to a dependency property definition Dependency Traditional B This table shows the minor syntactical differences between the traditional and dependency a Snippet 12.dk> .thiesen@seb. you’ll learn how to leverage the biggest advantage of a ENHANCING CLR PROPERTIES A DependencyProperty is a CLR property whose value is dynamically based on its data sources Table 12.3 Registering a DependencyProperty with the dependency system public static readonly DependencyProperty IsLockedProperty = DependencyProperty.Register( " B C# Licensed to SEB Link A/S .Henrik Thiesen <henrik. In addition.

dk> .thiesen@seb.2 The properties of the DependencyPropertyChangedEventArgs structure Description T Property NewValue OldValue Property This table shows the properties of the DependencyPropertyChangedEventArgs structure.Creating a user control typeof(LockableTextBox). DependencyPropertyChangedEventArg This snippet shows the event handler for the PropertyChangedCallback delegate specified in C# Licensed to SEB Link A/S .Henrik Thiesen <henrik. This s Snippet 12. new PropertyMetadata(new PropertyChangedCallback(OnIsLockedChanged 343 C# C This snippet shows how to register a property as a DependencyProperty. Notice the name of t RESPONDING TO PROPERTY VALUE CHANGES Dependency properties have the ability to automatically respond to property value changes i Table 12.4 Registering a DependencyProperty with the dependency system private static void OnIsLockedChanged(DependencyObject o.

com/winfx/2006 XAML B C This snippet shows how to add the LockableTextBox to a basic Silverlight page. First. you must add a Snippet 12. you must do two things.3 Calling the control To include a UserControl in your application.2 Architecting navigation in Silverlight Throughout this book.1. there seems to be a lot of additional coding associated with creating a de 12.dk> . you’ve learned about Silverlight from the perspective of an individua Licensed to SEB Link A/S .Henrik Thiesen <henrik.thiesen@seb.5 Using the LockableTextBox <UserControl x:Class="MySilverlightApp. The my names 12.Page" xmlns="http://schemas.microsoft.344 CHAPTER 12 Share the light: Distribution and deployment At first glance.

2 The architecture for providing navigation This figure shows a high-level overview of how to structure an application to support navig Snippet 12.dk> .xaml file <UserControl x:Class="Chapter12.Henrik Thiesen <henrik.6 The XAML of the NavigationService. Figure 12.thiesen@seb.Architecting navigation in Silverlight 345 items is selected. 12.1 Setting up the architecture Architecting your Silverlight application to provide navigation is fairly straightforward.2.com/winf B Licensed to SEB Link A/S .NavigationService" xmlns="http://schemas. the details will be loaded and displayed in a page called Details.xaml.microsoft.

2 Implementing a navigator To implement a navigator. foreach (UIElement child in root. public NavigationService() { InitializeCompo B C D E C# string currentPageType = currentPage.C F G H This snippet shows a basic implementation of the NavigationService class. which is a type of Pa 12. Although this loo Licensed to SEB Link A/S .346 CHAPTER 12 Share the light: Distribution and deployment This snippet shows a basic XAML file that includes a single Canvas B.dk> .Henrik Thiesen <henrik.7 The definition of the NavigationService class private static UserControl currentPage = null. you create the code to swap UserControl elements.2.GetType(). This code shoul Snippet 12.FullName.thiesen@seb.

2. This snippet shows an instance of the Master.a.k.Henrik Thiesen <henrik.dk> .Navigate(new Master()).8 The code to go back to the list view C# C# NavigationService. You should assume the item Licensed to SEB Link A/S . The third part is wh 12.Architecting navigation in Silverlight 347 which loads the default page of the application into the root Panel C.thiesen@seb. This snippet demonstrates how to load a page that requires data. Based on t Snippet 12. UserControls) To navigate from an XAML file to a new one. you must call the Navigate method defined in sn Snippet 12.xaml page created and navigated to.Navigate(new Details(item)).3 Navigating between pages (a.9 The code to load the details page into view NavigationService.

This task is important becaus 12.3.3 Using a custom splash screen Silverlight empowers you to create a consistent experience from start to finish. Part of th 12.xap file is being downloaded.Henrik Thiesen <henrik.dk> . You must take ■ ■ The splash screen is used while a . so it doesn’t make sense t With these constraints in mind. Licensed to SEB Link A/S . you can move forward with creating your own splash screen.1 Creating the appearance The first step in creating a custom splash screen is defining its appearance.thiesen@seb.348 CHAPTER 12 Share the light: Distribution and deployment for implementing navigation in your Silverlight applications.

Using a custom splash screen 349 Snippet 12. Assume this XAML is stored in a file cal Result <?xml version="1.dk> .10 The XAML for a custom splash screen.0" encoding="utf-8" ?> <Canvas Height="50" Width="200" xmlns="http: B XAML C D Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik.

2 Integrating the custom splash screen The second step of using a custom splash screen is integrating it with a web application.350 CHAPTER 12 Share the light: Distribution and deployment This snippet defines a basic animation within a Canvas element. This animation rotates an E 12.3. Y Snippet 12.Henrik Thiesen <henrik.11 The createObjectEx function call that associates a splash screen with Silverl <div id="parent1"> <script type="text/javascript"> Silverlight.thiesen@seb.dk> .createObjectEx ({ source: "C JavaScript B C This snippet uses the splashScreenSource property to reference the splash screen created in Licensed to SEB Link A/S .

Snippet 12.3.4 Hosting with Silverlight Streaming Silverlight Streaming is a free hosting service. that gives you seve Licensed to SEB Link A/S . provided by Microsoft.Henrik Thiesen <henrik. args) { // Retr JavaScript B C This snippet shows the onSourceDownloadProgressChanged B and onSourceDownloadComplete C eve 12.Hosting with Silverlight Streaming 351 12.thiesen@seb.12 The event handlers used for monitoring the download progress of a .xap file <script type="text/javascript"> function appDownloadProgressChanged(sender. but optional.dk> .3 Monitoring the load progress The third. step in creating a splash screen is monitoring the load progress.

you must create a manifest file.xaml file of a basic application <UserControl x:Class="MySilverlightApp. which will be compiled into a . Once you’re ready f DETAILING THE CONTENT To describe your Silverlight applications.13 The code for the Page. this se 12.4.4.352 CHAPTER 12 Share the light: Distribution and deployment To demonstrate how to request a Silverlight application from Silverlight Streaming.Henrik Thiesen <henrik.thiesen@seb. This manifest f Snippet 12.com/winfx/2006 This snippet displays a basic XAML file.2 Pack it up! Silverlight Streaming makes it easy to deploy Silverlight applications. Note that 12.14 The manifest file used to deploy a basic Silverlight application <?xml version="1.xap</sour XAML B C Licensed to SEB Link A/S .1 Preparing to stream! Creating content for Silverlight Streaming is no different than creating a standard Silverl Snippet 12.Page" xmlns="http://schemas.0" encoding="utf-8" ?> <SilverlightApp> <source>MySilverlightApp.xap file.dk> .microsoft.

dk> .3 The elements that can be used within the manifest.xml definition Element Source Width Background isWindowless frameRate inplaceInstallPrompt Version enableHtmlAccess onError onLoad jsOrder loadFunction Licensed to SEB Link A/S .Hosting with Silverlight Streaming 353 This basic Silverlight Streaming manifest file uses the SilverlightApp element to begin des Table 12.thiesen@seb.Henrik Thiesen <henrik.

3 Ship it! Deploying content through Silverlight Streaming is so simple that it hardly requires mentio 12.4.4 Use it! To use your uploaded content. which must be Table 12.354 CHAPTER 12 Share the light: Distribution and deployment managed code. the Silverlight Streaming service requires a single file. you must package a Silverlight applicatio COMPRESS IT! As you’ll soon see.thiesen@seb.dk> . you must target a web asset—you must have a web application r Licensed to SEB Link A/S . Regardless of which method you use.Henrik Thiesen <henrik.4.4 The file types accepted within a Silverlight Streaming application File type Aud 12.

thiesen@seb.live.15 Referencing a hosted Silverlight application JavaScript 1 <iframe src="http://silverlight.5 Summary Throughout this chapter.services.dk> .Summary 355 an authentication service to prevent any funny business.Henrik Thiesen <henrik.microsof Licensed to SEB Link A/S .com/invoke/7867/ My%20Silverlight%20App/ifram This snippet shows how to reference a Silverlight application hosted within Silverlight Str 12. Although they’re extremely valuabl Snippet 12. you’ve seen how Silverlight empowers you to deliver a rich experie You can find out more about the Silverlight Streaming APIs by visiting http://msdn.

Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik.thiesen@seb.

NET 200 framework 306 .Henrik Thiesen <henrik.thiesen@seb.index Symbols . 236 WCF 185 AngleX property 244 AngleY property 24 Numerics 96 dpi 74 A absolute file path 308 path 196 positioning 57 sizing 66–67 Uri 283 Abstract ASX element 20 Licensed to SEB Link A/S .dk> .NET Framework 7.

237 RadialGradientBrush 23 C C# 149 Calendar 110–112 restricting dates 112 selecting multiple dates 112 CalendarMode enu Licensed to SEB Link A/S . 43 Background property 12.358 AsyncCompletedEventArgs 331 asynchronous communication 164 downloads 321 service call 1 INDEX B background 34.Henrik Thiesen <henrik.thiesen@seb. 71. 117. 287 background tasks 316 cancellation 31 BasicHttpBinding 167 BasicHttpSecurityMode 167 Begin method 267 BeginGetRequestStream metho Fill 227 GradientBrush 12 ImageBrush 240 LinearGradientBrush 12.dk> .

thiesen@seb. See CSS Categories property 180 Center enume CommonStates visual state group 297 communication APIs 160 Completed event 268 CompletedSyn D daisy chain syntax 267 XAML support 266 dashboards 227 data binding binding source and targ Licensed to SEB Link A/S .INDEX 359 corner lower-right 237 upper-left 237. 243 CornerRadius property 121 cost effective med CaptureMouse method 94 Cascading Style Sheets.Henrik Thiesen <henrik.dk> .

unbind 128 data templates 139–141 DataContext property INDEX deployable archive file 352 deploying media from a web application 196 Deployment element 4 variants supported by Silverlight 25 W3C specification 24 domain element 161 DoubleAnimatio Licensed to SEB Link A/S .360 data integrity 163 data source.thiesen@seb.dk> .Henrik Thiesen <henrik.

thiesen@seb. state-based 298 element tree 86 ElementToLo Expression Blend 8. 303.dk> .Henrik Thiesen <henrik. 257 feed items 181 FileDialogFileInfo 120 FileMode 312 files . 245. Licensed to SEB Link A/S . 316 Brushes property editor 17 Objects and Timeli F fade animation 255.xap 282. 277.INDEX 361 reading files 313 writing files 311 Fill property 236 stretch option 224 FillBehavior p E Eastern Asian fonts 73 editing text 96 effects. 13–21.

Henrik Thiesen <henrik. 332 Gavrilov.thiesen@seb. 229.dk> . Alexey 3 Gecko 25 Generator property 181 geometries c GetStyleAttribute 47 GetStylusPoints method 123 GetTop method 58 GetUserStoreForApplication Height property 16. 287 HoldEnd enumeration value 263 horizontal offset 58 orienta I H Hand cursor 81 Handled property 42 handling text 96 handwriting 121 HasHeader property 110 Licensed to SEB Link A/S .362 fonts (continues) Trebuchet 73 TrueType 73 Verdana 73 FontSize animation 257 pixels ver INDEX G garbage collection 167. 65.

See filesystem IQueryable 154 IronPython 332–333 IronRuby 332 IsBusy property 324 IsChe J JavaScript 2.INDEX 363 Image 216.thiesen@seb. 54 creating a Silverlight control 28 custom K key combinations 91 key frame animation 271 types 273 Key property 91 keyboard 90 input lim L Language Integrated Query. See LINQ Language property 181 Licensed to SEB Link A/S . 89 calling from managed code 51. 340 animating the Opacity property 254 animation 259 data binding 134 pixelation IO.Henrik Thiesen <henrik.dk> .

monitoring 351 Loaded event 10.xaml Margin property 84. See AppManifest.dk> . 270 loadFunction manifest element 353 Lockab M manifest file 352 manifest file.thiesen@seb. 121 MarkerReached programmatically controlling playback 209 sound volume 203 streaming media 197 supported me Licensed to SEB Link A/S .364 languages dynamic 332 static 332 large download management 323 LastOperation property 1 INDEX load progress.Henrik Thiesen <henrik.

345 animation 257 Pa O OBJECT tag 31 Objects and Timeline panel 19 objects. 121 Page. 329. 331 OpenText method 120 Op P packaged XAML 30 Padding property 79.xaml 14 Panel 294. strongly typed 177 Offset property 237 Licensed to SEB Link A/S . See browser plug-in PNG image fo multiple color transitions 238 MultiScaleImage 217 composing dzi files 221 viewport 220 zoo N Name property 296 NaturalDuration property 200 NaturalVideoHeight property 203 NaturalVideo OpenReadCompleted event 325 OpenReadCompletedEventArgs 327.thiesen@seb.dk> .INDEX 365 PlayReady 213 installation 214 server SDK 215 plug-in. 340.Henrik Thiesen <henrik.

thiesen@seb. 25 safeguards full-screen mode restriction 213 limits to user input 213 ScaleTran Licensed to SEB Link A/S . 228–229 animation 265 dynamic loading from XAML 315 rectangle bulging 229 reusable components 279 controls 339 templates 295 RGB 236 aRGB format 236 RxGyBz format 23 S Safari 5. 349 RadioButton 102 grouping 103 RadiusX property 239 RadiusY Rectangle 12.Henrik Thiesen <henrik. 16.dk> .366 protocols HTTP 196 HTTPS 196 MMS 196–197 Silverlight 196 PublishDate property 182 INDEX Q QuadraticBezierSegment 234 query operations Average 150 Cast 150 Concat 150 Count 150 Disti R RadialGradientBrush 238. 247.

dk> . See Silverlight SDK security atta shearing transform 243 ShowDialog method 119 ShowGridLines property 63 Silverlight accessin Licensed to SEB Link A/S .thiesen@seb. 244 security safeguards 213 SMIL elements supported 208 SOAP ScriptableMember 52 ScriptableType 52 ScriptAlias 52 SDK.INDEX 367 protocols 196 SDK 26.Henrik Thiesen <henrik. 141.

340 layout of invisible elements StylusDevice property 93 StylusPoint 124 submitting form data 170 Summary property 182 Swit Licensed to SEB Link A/S . 294.dk> .368 SilverlightApp element 352 Silverlight-Enabled WCF Service 185 SilverlightHost 43. INDEX SQL 149 SSL 167 stack order 59 StackPanel 61–62.Henrik Thiesen <henrik.thiesen@seb. 103. 53.

345 capturing the mou Licensed to SEB Link A/S . 80.Markup namespace 314 Sys T TabControl 108 defining look and feel 109 TabItem 108 visual tree 108 TabStripPlacement pro TextBlock 8. 89. 350 aligning text 78 animation 257 dynamically downloade U UI separation 6 updates 171 virtualization 142 UIElement 57.dk> . 140 TotalBytesToReceive property 323 track 116 Transform 242–245 t System. 91.Windows. 95. 251 System. 72.thiesen@seb. 340. 186.INDEX 369 ToString method 135. 124. 167. 57.Henrik Thiesen <henrik.Input namespace 81.Windows.

Henrik Thiesen <henrik. 327 absolute 283 relative INDEX V Value attribute 288 property 116. 197 destination 171 relative 283 Uri 101. Licensed to SEB Link A/S . 272 values EvenOdd FillRule 235 Nonzero FillRule 235 vari visibility modes All 146 Collapsed 145 Column 147 Row 147 VisibleWhenSelected 146 Visibilit wildcard characters 307 Window property 48 Windows Communication Foundation.370 URI 167.dk> . 322.thiesen@seb. 284. See WCF Window X W W3C 24 Wait cursor 81 wax file 205 WCF 185 duplex services 186 web property 23 web server.

179 XmlSerialize Z ZIndex property 59 zip file 328. 31 XML 322. 354 extracting contained files 329 zoom in 243 out 243 Zoo Y Y property 244 Licensed to SEB Link A/S .dk> .thiesen@seb. 325 namespace 315 xmlns attribute 10. 175–176.INDEX 371 XAML (continued) runtime parsing 314 switching between files 344 XamlParseException 281. 315 XmlReader 156.Henrik Thiesen <henrik.

Sign up to vote on this title
UsefulNot useful