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>

3 Integrating a Silverlight plug-in ■ 29 Relating the Silverlight application to the HTML DOM 30 Clarifying the initial experience 3 ■ 2.2 Creating a Silverlight plug-in 26 27 ■ The Silverlight utility file: Silverlight.4 The Silverlight Application Model The manifest file application 41 ■ ■ 39 44 40 The Silverlight Application dependencies 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.viii CONTENTS 2.1 A Canvas for your imagination Arranging content of a Canvas packing a punch 60 58 56 57 ■ .js instance of the Silverlight plug-in 28 Creating an 2.6 Summary 55 3 Back to the basics: Layout and text 3.

The Canvas: 3.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.Henrik Thiesen <henrik.2 3.6 The UIElement and FrameworkElement Properties 80 ■ 80 Methods 85 Summary 86 4 Handling user interaction 4.5 3.1 Capturing the keyboard 88 89 92 89 ■ Understanding device support Trapping the mouse Licensed to SEB Link A/S .4 Displaying text ■ 72 ■ Font properties 72 Flow control properties 76 Spacing 78 76 ■ Text 3.dk> .

6 4.7 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 ■ .8 4.2 4.CONTENTS ix 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.5 4.4 The ItemsControl 105 The ListBox 105 The ComboBox The TabControl 108 ■ 107 4.

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

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

5 Summary 193 7 Managing digital media 7.1 ■ 159 160 Trust. and browser limitations ■ It’s all a matter of trust 160 Making your application secure 163 Limitations of the browse 6.x CONTENTS 6 Networking and communications 6. security.4 Using advanced services ■ 185 ■ WCF service enhancements 185 WCF duplex services 186 Connecting to sockets 191 6.1 194 ■ .2 6.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.

2 Playlists: for that web-based mixtape 205 Understanding client-side playlists playlists 207 205 ■ Using server-side 7.5 7.thiesen@seb.4 Using protected content 213 Requesting protected content 214 Retrieving the PlayReady components 214 Unlocking protecte ■ ■ 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 .7 Summary 225 8 Getting a grip on graphics 8.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.Stunning audio and video 195 Getting to the source 195 Common properties 199 Audio specifics 201 Video specifics 203 The ■ ■ 7.Henrik Thiesen <henrik.3 Interactive playback 209 Controlling the play state 209 Timely interaction 210 Going full screen 212 ■ ■ 7.dk> .

.

3 Brushes 235 ■ ■ SolidColorBrush 236 LinearGradientBrush 237 RadialGradientBrush 239 ImageBrush 240 VideoBru 8.5 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.2 Geometry 231 ■ Simple geometries 232 Path geometries Composite geometries 235 233 8.4 Key framing 271 Interpolation: It’s about acceleration is everything 276 273 .4 Transforms 242 ■ ■ RotateTransform 242 ScaleTransform 243 SkewTransform 243 TranslateTransform 244 TransformGr 8.1 9.6 Blending it together Summary 251 245 9 Bringing it to life: Animation 9.CONTENTS xi 8.3 Storyboarding 264 Understanding the storyboard 264 Hitting the target 265 Controlling the Storyboard 267 Bein ■ ■ ■ 9.

2 10.■ Timing 9.dk> .thiesen@seb.Henrik Thiesen <henrik.1 278 ■ Being resourceful 279 Declarative resources 279 Accessing loose resources 282 Bundling resources 284 ■ 10.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.5 Summary 277 10 Giving it style 10.4 Dealing with visual states 295 296 Understanding the components Licensed to SEB Link A/S .

2 .7 Leveraging the VisualStateManager 298 Sharing your effects 301 Summary 303 11 Enhancing the experience 11.3 11.6 The Dynamic Language Runtime (DLR) Dynamic typing 332 ■ 332 335 Metaprogramming Summary 337 12 Share the light: Distribution and deployment 12.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 Creating a user control 339 Defining the appearance 339 Defining the behavior 340 Calling the control 344 ■ ■ 338 12.1 305 ■ Storing data in isolated storage 306 IsolatedStorageFile: The virtual filesystem 306 Reading and writing files: The isolated sto ■ 11.xii CONTENTS 10.5 10.5 11.6 10.2 11.

k.5 Summary index 357 355 Licensed to SEB Link A/S .Henrik Thiesen <henrik. 12.dk> .Architecting navigation in Silverlight ■ ■ 344 Setting up the architecture 345 Implementing a navigator 346 Navigating between pages (a.thiesen@seb.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.

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

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

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

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

thiesen@seb.dk> .bubblemark.Henrik Thiesen <henrik.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.com website that compa xvii Licensed to SEB Link A/S .

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

dk> .thiesen@seb.Henrik Thiesen <henrik.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 .

Henrik Thiesen <henrik.thiesen@seb. the best xx Licensed to SEB Link A/S .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. we’ve created a companion website.dk> .

web-based user The gear: what you need This book provides a lot of opportunity for hands-on learning. Silverlight 2 Beta 2. Silverlight 2 Beta 1.dk> . 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. this list may be somewhat overwhelming.Henrik Thiesen <henrik. But.thiesen@seb.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. valuable.1 Alpha. and finalized on Silverl If you’re new to these tools. If you’d like a guide Licensed to SEB Link A/S .

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

if you in About the authors Chad Campbell is a Microsoft MVP and solutions architect.com Chad’s blog—http://cornucopia30.blogspot.co All comments sent to these blogs are moderated. 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.Henrik Thiesen <henrik.silverlightinaction. He has been developing enterprise Licensed to SEB Link A/S . but.thiesen@seb. We post nearly all comments. This includes user Code conventions All the code used in this book will be presented in a monospace font.dk> .ABOUT THIS BOOK xxiii Chapter 12 discusses sharing your Silverlight creations with the world.

Henrik Thiesen <henrik.thiesen@seb.xxiv ABOUT THIS BOOK In addition.” J Licensed to SEB Link A/S . 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.dk> . overviews.

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

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

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 .Henrik Thiesen <henrik.dk> .thiesen@seb.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.

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

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

per technology. per platform. and per browser2 Those interested in Silverlight often ask: What does everywhere really mean? Well.4 CHAPTER 1 Introducing Silverlight Figure 1.2 Silverlight supports the platforms listed.1 Calculated frames per second. natively Figure 1.Henrik Thiesen <henrik. 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 .dk> .thiesen@seb.

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

Henrik Thiesen <henrik.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.thiesen@seb.dk> .6 CHAPTER 1 Introducing Silverlight 1.2 Why can’t we be friends? Traditionally.

thiesen@seb.NET.3. (Or is it Licensed to SEB Link A/S .Why can’t we be friends? 7 The details of XAML are covered in section 1.Henrik Thiesen <henrik.dk> . For now.2.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: . it’s important to understand that Developer Designer User Interface Logic Data Sources User Interface Logic Figure 1.

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

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

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

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

Page" xmlns="http://schemas.NET types Snippet 1.3. 1.6 shows the relationship between XAML and .12 CHAPTER 1 Introducing Silverlight XAML-related concepts that we should discuss—the least of which is the incredibly powerful compound property feature.3 A Grid with a gradient background <UserControl x:Class="CompoundProperties01.com/client The concept of a GradientBrush is discussed in chapter 8.3 Compound properties Although the illustration in figure 1. you define t 1.dk> . but.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 .microsoft. as you can see.3.Henrik Thiesen <henrik.thiesen@seb.

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

microsoft. Once the Silverlight project is loaded within Visual Studio. O <UserControl x:Class="Welcome. At this point.Henrik Thiesen <henrik.Page" xmlns="http://schemas. This dialog bo 6 7 Click OK.thiesen@seb. the Page. the Add Silverlight Application dialog box appears. enter the following project prop 5 Click OK.com/winfx/2006/xaml/pre Licensed to SEB Link A/S .dk> .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.14 4 CHAPTER 1 Introducing Silverlight Once you’ve selected the Silverlight Application template.

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

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

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.thiesen@seb.dk> .Henrik Thiesen <henrik. Select the Gradient Brush tab within the Brushes category and Licensed to SEB Link A/S .

hiding it. If you were to r Licensed to SEB Link A/S . you have a Rectangle on top of the MediaElement.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.Henrik Thiesen <henrik.thiesen@seb.dk> . such as #FF383737. 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. as shown i Add a new gradient stop by clicking the middle of the gradient slider.

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. make sure the Rectangl 16 17 Press F5 to run the application. To do this.Henrik Thiesen <henrik.thiesen@seb. Notice how this is consistent with Visual Studio.dk> . Close th This walk-through demonstrates how you can open Silverlight projects created from Visual St Licensed to SEB Link A/S .

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

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

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

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

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

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.1.thiesen@seb.1.3 The Silverlight Object Model The Silverlight Object Model is represented as a hierarchical tree structure.Henrik Thiesen <henrik.dk> . These DOM variants and their descriptions ar 2.2 The Silverlight plug-in The Silverlight plug-in is a lightweight browser plug-in responsible for rendering Silverli 2.The relationship between Silverlight and the HTML DOM Table 2. This tree str Licensed to SEB Link A/S .

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

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

7 JavaScript A sample Silverlight plug-in onError event handler function plugin_Error(sender. } This snippet shows an extremely basic onLoad event handler.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. } This snippet shows an all-purpose onError event handler. The event handler can be used to g Licensed to SEB Link A/S ."). errorArgs) { alert("An unexpected error has occurred. W Snippet 2.dk> .Henrik Thiesen <henrik. This event handler shows the th Table 2.thiesen@seb. 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. context. source) { alert("loaded").6 JavaScript A sample Silverlight plug-in onLoad event handler function plugin_Load(sender.Integrating a Silverlight plug-in 37 the option of creating an event handler for when this event fires. Regardless of how you in Snippet 2.

38 CHAPTER 2 Harmony with the web sender argument will represent the plug-in where the error occurred. This parameter is a val 2.dk> .createObjectEx({ source: "ClientBin/MySilverlightApp. variety of publicly visible properties.3. imagine Snippet 2. The second parameter.thiesen@seb.NET application. As an example.8 Registering initialization parameters with a plug-in instance Silverlight.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.xap". These properties are listed and described in table Table 2. parentElement: docum HTML Licensed to SEB Link A/S .Henrik Thiesen <henrik.4 Sending initialization parameters A Silverlight application is a lot like any other .

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

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

2 The Silverlight application The entry point into the Silverlight application is the App object.4. 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 . the Startup event fires.dk> .The Silverlight Application Model 41 2.10 A sample Startup event handler private void Application_Startup(object sender. this event loads Snippet 2. By default.thiesen@seb. StartupEventArgs e) { IDictionary<string.Henrik Thiesen <henrik. This object is defined MANAGING THE START OF A SILVERLIGHT APPLICATION Once the App object has been created.

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

you can retrieve information about the ho Snippet 2.dk> .Henrik Thiesen <henrik. The firs Table 2.Current.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.thiesen@seb.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.Host.12 Retrieving settings associated with hosting plug-in C# Application application = Application. These propert Licensed to SEB Link A/S .

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

NAVIGATING WEB PAGE CONTENTS The HtmlDocument gives you two entry points into the currently loaded document. More specifically.Document. the Table 2.GetElementById Note that the “myDiv” element is simply an HTML DIV element within the HTML page hosting th Licensed to SEB Link A/S .Interacting with the HTML DOM 45 tionality.dk> .thiesen@seb.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.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.13 Referencing an HTML element via managed code C# HtmlDocument document = HtmlPage. The Silverlight version gives you the ability to do all this from managed code.

GetElementByI C# B C This snippet shows how the GetProperty and SetProperty methods can be used.46 Table 2.dk> . Some of these prop Snippet 2.thiesen@seb.14 Using the GetProperty and SetProperty methods HtmlDocument document = HtmlPage.Henrik Thiesen <henrik.Document. Note that this Licensed to SEB Link A/S . HtmlElement myTextField = document.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.

HtmlElement myDiv = document.Document.GetElementById("myD B This snippet shows how to use a style attribute from managed code.dk> .thiesen@seb. The presen Snippet 2. 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 .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.15 Assigning a style attribute from managed code HtmlDocument document = HtmlPage.Henrik Thiesen <henrik.

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

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

Henrik Thiesen <henrik.19 Launching the official Silverlight 2 in Action website in a new browser window Uri uri = new Uri("http://www.12 properties Descriptions of the BrowserInformation properties and their correspon BrowserInformation BrowserVersion Navigator appVersion Description Represents the platform and version associated with the browser.11 Snippet 2.50 Table 2. Specifies whet CookiesEnabled cookieEnabled Licensed to SEB Link A/S .silverlightinaction.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. These two options are shown in table 2.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.thiesen@seb.dk> . HtmlWindow window = HtmlPage.com").

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

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. Licensed to SEB Link A/S .52 CHAPTER 2 Harmony with the web Once these tasks have been performed.thiesen@seb.23 Exposing an object to the scripting world public Page() { InitializeComponent().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.dk> . you’re free to reference the managed elements from Ja Snippet 2. This attribute gives Snippet 2.Henrik Thiesen <henrik.

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

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

6 Summary Silverlight was designed to be consistent with the well-established web architecture.thiesen@seb. This Licensed to SEB Link A/S .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.dk> .Henrik Thiesen <henrik.

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

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

Canvas.1. The first SETTING THE OFFSETS By default.Henrik Thiesen <henrik.SetLeft(tb. 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 .58 CHAPTER 3 Back to the basics: Layout and text 3. But.GetLeft(tb) + 15. this approach place Snippet 3. newLeft). the content within a Canvas is automatically arranged.4 Changing the position of an element at runtime C# double newLeft = 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.Top="30" /> The TextBlock uses the Left and Top attached properties to set its position within an imagi Snippet 3.dk> .Left="20" Canvas.thiesen@seb.

ZIndex="2" Width="60" Height="60" Backgr XAML Licensed to SEB Link A/S . 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.A Canvas for your imagination 59 you may inadvertently overlap the content within a Canvas.thiesen@seb.dk> .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. when content is rendered within a layout panel. each element is rendered on its Snippet 3. Although this overlapping effect SETTING THE STACK ORDER By default.Henrik Thiesen <henrik.6 Result Using the ZIndex to move an element into the foreground <Canvas> <Canvas x:Name="myCanvas"> <Canvas Canvas.

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

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. I found myself immersed in a fun-filled cros Snippet 3.Henrik Thiesen <henrik.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 .2 The StackPanel: Stack ’em deep Personally.dk> .The StackPanel: Stack ’em deep 61 the Welcome text to other languages.thiesen@seb. Table 3. after I (Chad) awoke this morning.

37 Quantity 5 4 27 Total Total $1.3 The power Grid The Grid panel gives you the ability to easily lay out content in a tabular format.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.dk> .25 XAML Candy Beans $0. shifting the layout from a vertical to horizontal orientati Item # 1 2 3 Description Lollipops Gum Price $0.03 Figure 3.thiesen@seb. This ta Licensed to SEB Link A/S .25 $0.62 CHAPTER 3 Back to the basics: Layout and text Snippet 3.2 A basic purchase order Imagine attempting to re-create the purchase order shown in this figure using a series of S 3.Henrik Thiesen <henrik.

thiesen@seb.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 .RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowD E F This snippet defines a Grid with three columns D and three rows F.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. The rows and columns of 3.Henrik Thiesen <henrik.3.dk> . As you’d expect. this element generally se Snippet 3.The power Grid 63 defined within the ColumnDefinitions collection.

11 Arranging content within a Grid Result <Grid x:Name="myGrid" ShowGridLines="True" Background="LightGray" Width="310" Height B C <TextBox Width="150" Grid.64 CHAPTER 3 Back to the basics: Layout and text how to arrange content in a Grid.Henrik Thiesen <henrik. These two a Snippet 3.12 The basic syntax of the Column and Row attached properties XAML <TextBlock Text="Rock On!" Grid.Row="3" Grid. which will be used to create a basic input form (snippet Snippet 3.Row="1"></TextBox> <TextBox Width="150" Grid.Column="1" Grid.dk> . The proper Licensed to SEB Link A/S .thiesen@seb.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.Column="2" /> This line of XAML illustrates how to use the Row and Column attached properties.

thiesen@seb. you run into situations where you need to allow content to span multiple cell Snippet 3.Column="1" Grid.dk> .3.Row="1" Grid.RowSpan="1" Grid.The power Grid 65 If you attempt to assign an element to a row or column that doesn’t exist.13 The syntax of the ColumnSpan and RowSpan attached properties XAML <TextBox Grid. Oc 3.ColumnSpan="2" /> The ColumnSpan and RowSpan properties are easy to add to any piece of content in a Grid. the element will SPANNING CELLS Occasionally.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 .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.14 A basic Grid using star sizing. But first. Absolute sizing AUTOMAGICALLY The Auto GridLength option automatically determines how large or small to make an element.Henrik Thiesen <henrik.dk> . Licensed to SEB Link A/S .66 CHAPTER 3 Back to the basics: Layout and text approach.thiesen@seb.

dk> .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.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 .The power Grid 67 Snippet 3.Henrik Thiesen <henrik.

myGrid.3 Working with the Grid programmatically Usually.thiesen@seb.RowDefinitions> <RowDefinition Height="68. myGrid C Licensed to SEB Link A/S .Henrik Thiesen <henrik.RowDefiniti C# B // Programmatically add a Column ColumnDefinition myColumn = new ColumnDefinition().17 Programmatically adding a row and a column while setting the height and width // Programmatically add a Row RowDefinition myRow = new RowDefinition().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.5"></RowDefinition> <RowDefinition Height=" B This snippet shows the absolute sizing approach in action. The rows use a double-precision 3.dk> .3. 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.

These a Snippet 3.18 Programmatically removing a row and a column // Programmatically remove the first Row RowDefinition myRow = myGrid.thiesen@seb.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 .16. you must use one of two approaches.C C This snippet shows two methods for programmatically removing rows and columns from a Grid.Henrik Thiesen <henrik. my C# B // Programmatically remove the last Column int lastColumnIndex = myGrid.The power Grid 69 This snippet adds a row and a column to the Grid created in snippet 3.ColumnDefinitions.dk> .RowDefinitions[0].3. The first approac REMOVING ROWS AND COLUMNS AT RUNTIME To remove either a row or a column from a Grid. 3.

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

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

This p 3. These properti Licensed to SEB Link A/S . the Grid is the most powerful layout panel in Silverlight because it can do alm 3.thiesen@seb.72 CHAPTER 3 Back to the basics: Layout and text In general.1 Font properties The TextBlock has five properties related to the styling of a selected font.4.4 Displaying text Text is an important part of any presentation technology.Henrik Thiesen <henrik. Snippet 3.dk> .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.

thiesen@seb.3 shows the nine TrueType fonts supported within Silverlight. In addition to these Licensed to SEB Link A/S .Henrik Thiesen <henrik. the TextBlock displays text using the Lucida Sans Unicode font on Windows machi Figure 3.Displaying text Table 3.3 A sampling of the font families supported within Silverlight Figure 3.dk> .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.

) The FontSize property empowers you to se Snippet 3. In addition to setting the FontSi FONTWEIGHT The FontWeight property represents the heaviness of the displayed text. 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 .22 Setting the FontSize at design time XAML <TextBlock Text="I’m a Big Boy Now.dk> .74 FONTSIZE CHAPTER 3 Back to the basics: Layout and text n x 96 (n represents the number of points to use.thiesen@seb.Henrik Thiesen <henrik." FontSize="32" /> This basic line of XAML sets the FontSize to a 24pt font.

But with Silverlight. 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.Italic.Henrik Thiesen <henrik. This static proper Licensed to SEB Link A/S .dk> .Displaying text 75 Table 3.FontStyle = FontStyles.24 Setting the FontStyle at runtime myTextBlock.thiesen@seb. Setting the FontStyle during ru Snippet 3. Notice how this snippet uses a FontStyles static property called Italic.4 The acceptable values for the FontStretch property are listed under the Name colu tional web application.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.

4.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.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.Henrik Thiesen <henrik. Silverlight goes beyond basic font styling and gives you the abilit 3.thiesen@seb. Licensed to SEB Link A/S .2 Flow control The TextBlock enables you to control the overall flow of text through two nested elements.76 CHAPTER 3 Back to the basics: Layout and text styling of a TextBlock.dk> . Snippet 3.4. More specifically.

section 3. <TextBlock Text="I m Serious" TextDecorations="Underline" /> Much like the FontStyle property. The various Brush options are not covered until chapter 8. This can be accomplis Snippet 3.Henrik Thiesen <henrik. For now Snippet 3.1) TEXTDECORATIONS The TextDecorations property gives you the ability to underline text.thiesen@seb. 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.dk>   .3.27 Underlining text in a TextBlock.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 .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.Displaying text 77 solid colors.

You Snippet 3.Henrik Thiesen <henrik. 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.30 The relationship between the FontSize and LineHeight properties Result XAML Licensed to SEB Link A/S .4 Spacing Spacing is effective for making text easier to read.thiesen@seb. Center.dk> .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.29 The Left. and Right TextAlignment options Result <Canvas Width="640" Height="480" Background="White"> <TextBlock Text="Everybody to t This snippet demonstrates the invaluable TextAlignment options.4. These options provide one w 3.

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. You XAML XAML Licensed to SEB Link A/S .Displaying text 79 <Canvas Height="450" Width="485"> <TextBlock Width="110" LineHeight="1" FontSize="14" TextW B As this snippet illustrates. This space Snippet 3. 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.2 pixels creates a nice bubble around some text.

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

the cursor will change to i Snippet 3.dk> .5 An example of the Opacity property Licensed to SEB Link A/S . Table 3. this double-pre Figure 3.thiesen@seb.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. Because of the abstract nature of the UIElement and CURSOR When a user navigates the mouse cursor over a FrameworkElement.5 The Cursor elements These optio OPACITY The Opacity property represents the transparency of an element. By default.The UIElement and FrameworkElement 81 enhance your applications in new ways.Henrik Thiesen <henrik.

thiesen@seb.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. By default.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. each of these elements has a Visibil Snippet 3.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. 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 .dk> .Henrik Thiesen <henrik.

This grid contain This figure shows a common feature found in almost any web application.Henrik Thiesen <henrik.thiesen@seb.The UIElement and FrameworkElement 83 Figure 3.6 The figure on the left represents a page that displays a grid.dk> . 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> .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.thiesen@seb.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.37 The darker area represents the Margin. the Margin property enables you to specify a cus Snippet 3.

MouseButtonEventArgs e) { double top = Conver C# C D Licensed to SEB Link A/S . A DependencyObject gives you the ability to Snippet 3.Henrik Thiesen <henrik.2 Methods Two common tasks are often performed during runtime.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. This may cause a bit 3.The UIElement and FrameworkElement 85 This snippet shows the Margin and Padding properties working together.dk> .5.thiesen@seb. The first task involves managing attac MANAGING ATTACHED PROPERTIES Every UIElement represents a DependencyObject.

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

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

dk> .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 .Henrik Thiesen <henrik.thiesen@seb.

1 The JavaScript that gives focus to a Silverlight control so that it can accept JavaScript var silverlightControl = document.dk>     .1 Understanding device support Real-world applications need a way to accept input from users.getElementById( SilverlightControl ).Henrik Thiesen <henrik. if (silv Licensed to SEB Link A/S . These controls provide interesting features that will be us 4.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. This process of collecting i 4. it becomes the primary target for any information entered throug Snippet 4.thiesen@seb.1.Understanding device support 89 trols that don’t fit elsewhere.

Key This snippet shows a page in Silverlight that responds to the KeyDown and KeyUp events. KeyDown and Snippet 4.microsoft.com/winfx/2006/xaml/ XAML B public partial class Page : UserControl { public Page() { InitializeComponent(). KeyEventArgs e) { myTextBlock.Page" xmlns="http://schemas. These events.2 A page in Silverlight that responds to the KeyDown and KeyUp events.dk> . this. The event <UserControl x:Class="Keyboard01.Henrik Thiesen <henrik.KeyUp C D private void Page_KeyUp(object sender.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. The Licensed to SEB Link A/S .thiesen@seb.Text = "Key (" + e.

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

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

dk> .1 In order to be consistent across platforms.4 lists the properties available through the MouseEventArgs class.4 The properties exposed by the MouseEventArgs Description A bool that flags whethe Property Handled StylusDevice Table 4. Silverlight 2 doesn Table 4.Henrik Thiesen <henrik.thiesen@seb. 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 .Understanding device support Table 4.3 The click-related events associated with the mouse Event MouseLeftButtonDown Desc 93 MouseLeftButtonUp have a right mouse button.

94 Table 4.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. Release the object and drop The first step in the drag-and-drop process involves selecting the object to drag.dk> .thiesen@seb. In order Licensed to SEB Link A/S . Move the object to the new location.5 undoubtedly separate the mouse from the keyboard. 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.Henrik Thiesen <henrik.

thiesen@seb.4 The mouse-related event handlers for implementing drag-and-drop private bool isMouseDown = false. private Point lastPoint = new Point().Henrik Thiesen <henrik.dk> .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 .

you can begin collecting items such as 4.Henrik Thiesen <henrik.2 Delivering text controls Once you can respond to events from an input device. By default. this featur Licensed to SEB Link A/S . i Snippet 4. This value will change if a ENABLING MULTILINE TEXT SUPPORT The TextBox has built-in support for handling multiline text input. As basic as this may sound. 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.5 The default look of a TextBox.thiesen@seb.1 Handling basic text The TextBox control enables your users to edit and view text.96 CHAPTER 4 Handling user interaction 4.2.dk> .

6 A multiline text box.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.thiesen@seb. multiline text boxes ar Result <Grid> <Grid. In line-of-business applications.dk> .Delivering text controls 97 Snippet 4. A user ca XAML Licensed to SEB Link A/S .

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

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

100 CHAPTER 4 Handling user interaction The ClickMode enumeration can be used to define a small part of the behavior of a button. As you progress t 4.Content> <TextBox HorizontalAlignment="Stretch" Hei <Button Padding="10" Height="120" Width="180"> <Button.3. X B B <Button Height="30" Width="90"> <Button.thiesen@seb.7 Button The flexibility of a ContentControl is displayed in these three buttons.Henrik Thiesen <henrik.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 . T Table 4.dk> .

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

102 Table 4. or _top whitespace characters.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 . _media.Henrik Thiesen <henrik. For instance. or _search _parent. A ToggleButton represents a button that can change Snippet 4.thiesen@seb. _self.dk> . the NavigateUri will load in a new window.3 The RadioButton A RadioButton represents a choice within a group of options. imagine having t RADIOBUTTON SELECTION A RadioButton is a kind of ToggleButton.3.8 CHAPTER 4 Handling user interaction The acceptable options for the TargetName property Target Value Description Launches the UR _blank. It’s important to remembe 4.

You can see that the first option is RADIOBUTTON GROUPING A grouping of RadioButton items represents the choices available for a single situation.Button controls 103 This snippet shows two options for a single question.dk> .thiesen@seb. In Snippet 4.Henrik Thiesen <henrik.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 .

3.4 The CheckBox The CheckBox control enables a user to select whether or not an option is chosen. Unlike th Snippet 4.Henrik Thiesen <henrik.13 shows the look and syntax of a three-state CheckBox.thiesen@seb.dk> .13 Using three-state mode check boxes Result <StackPanel> <CheckBox IsThreeState="True" IsChecked="False" Content="Unchecked" /> Snippet 4. The fact that the CheckBo XAML XAML Licensed to SEB Link A/S .104 CHAPTER 4 Handling user interaction 4.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.

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

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

The ItemsControl 107 This snippet shows a ListBox control with much richer ListBoxItem elements than those shown 4. As you can see. In chapter 5.16 shows the appearance of a closed ComboBox.16 A ComboBox that has been used to select an item Result <ComboBox x:Name="myComboBox" Height="28" Width="180"> <ComboBox.4.Henrik Thiesen <henrik.dk> . Thes Snippet 4. this control delive 4 Snippet 4.Items> <ComboBoxIte Snippet 4.thiesen@seb.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 .14 merges the UI with the data used in the list.

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

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.Henrik Thiesen <henrik.dk> . which includes a basic TabControl.

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

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

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. By defaul Licensed to SEB Link A/S . By default. which happens to be a DayOfWeek value.Henrik Thiesen <henrik. This value defaults to EMPOWERING DATE SELECTION The Calendar control enables you to restrict the dates that can be selected.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.dk> . th Table 4.112 Table 4.thiesen@seb.

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

Henrik Thiesen <henrik.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.114 CHAPTER 4 Handling user interaction Table 4. For insta Table 4.thiesen@seb.11 The options that can be used to format the SelectedDate. Because th Licensed to SEB Link A/S . These options can be us Short 5/1/2008 4.dk> .6 Choosing from a numeric range Imagine a scenario where you need to select or see a value between two endpoints.

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

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

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

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.Henrik Thiesen <henrik.7.118 CHAPTER 4 Handling user interaction Popup. you must instantiat Licensed to SEB Link A/S . Instead. you must manually set them. This is also true when you are deciding on posi POSITIONING THE POPUP Positioning a Popup is slightly different than positioning other FrameworkElement objects.thiesen@seb. 4. or multiple files.dk> .

thiesen@seb.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 .dk> .13 Result OpenFileDialog openFileDialog = new OpenFileDialog(). you have flexibility in customizing the selection experience.Henrik Thiesen <henrik. but y Snippet 4.25 Creating an OpenFileDialog using the properties from table 4.Displaying visual prompts Table 4.13 The configuration properties available on the OpenFileDialog Description This st 119 Property Filter FilterIndex Multiselect As this table displays. openFileDialog.

you can see that once a user opens the dialog box. the ShowDialog method will return a nullable bool valu Snippet 4. if (fileWasSelected == true) { FileInf From this snippet.OpenText().dk> . working with a text file in Silverlight is incredibly trivial. It’s C# Licensed to SEB Link A/S . File.thiesen@seb. The contents of a selected file FileInfo fileInfo = openFileDialog. StreamReader reader = fileInfo.ShowDialog().27 Retrieving the selection of an OpenFileDialog.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. myText As this snippet shows. 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.Henrik Thiesen <henrik.

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

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

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 .31 Finishing the Stroke public void ipMouseLeftButtonUp(object sender. MouseButtonEventArgs e) { myInkPresenter.dk> .Rel This snippet completes the process of drawing a Stroke on an InkPresenter.stroke != null) { this.Henrik Thiesen <henrik.30 Adding to the Stroke through the MoveMove event public void ipMouseMove(object sender. This r Snippet 4.thiesen@seb. You’ll notice that this task Snippet 4. 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.29. MouseEventArgs e) { if (this.

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

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

thiesen@seb.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 .Henrik Thiesen <henrik.

This illustration uses the situation of binding the current time of day to a TextBox to giv 5. Figure 5.1 A conceptual view of data binding.Henrik Thiesen <henrik.dk> .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 . This chapter will end with an overview of the distinguishing data querying enhanc 5.1.1 Mastering the binding syntax Silverlight gives you the ability to create a Binding using two different approaches.1 Binding with your data Data binding is a powerful way to create a connection between your UI and a source of data.Binding with your data 127 DataGrid.

Now. Text = "Binding Removed".Henrik Thiesen <henrik.2 C# C# Removing a Binding from a TextBox myTextBox.Text = "Binding Removed". binding. binding. 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 .1 XAML Adding a Binding to a TextBox from C# <TextBox x:Name="myTextBox" /> DateTime currentTime = DateTime.128 CHAPTER 5 Getting down with data binding Snippet 5. This Snippet 5. B C D Binding binding = new Binding("TimeOfDay").Mode = Bi This snippet shows how to bind the value of a CLR property to a UI element at runtime. This snippet shows how easy it is to remove a binding after it has been set.dk> .thiesen@seb.Source = currentTime.

myTextBox.Binding with your data 129 approach if you’ve used ASP. This binding is associated with 5.Now. If you haven’t. don’t worry.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 .3 XAML Binding a property to a TextBox in XAML <TextBox x:Name="myTextBox" Text="{Binding TimeOfDay.DataContext = currentTime. Mode=OneWay}" /> B DateTime currentTime = DateTime.Henrik Thiesen <henrik.thiesen@seb. this appro Snippet 5.1.dk> .NET or WPF. C# C This snippet shows how to create a binding at design time. In essence.

the source is updated.thiesen@seb.2 A conceptual view of OneTime binding to a data source be automatically sent to the target. If the target changes. This option gi Figure 5.dk> . 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 process can be seen in f Licensed to SEB Link A/S . Instead. This may sound r source changes. Think of the speedomete TWOWAY TwoWay binding enables two properties that are bound to change each other.Henrik Thiesen <henrik.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.

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

thiesen@seb. For instance.Henrik Thiesen <henrik.ComponentModel namespace’s INotifyPropertyCh 1 An emoticon is a symbol that represents a feeling or emotion.dk> . This e Snippet 5.132 CHAPTER 5 Getting down with data binding A change-notification handler notifies a binding target that a change has been made.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. :) is the sign Licensed to SEB Link A/S .

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

Column="1" /> XAML <TextBox Text="{Binding Name.Henrik Thiesen <henrik.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.2.134 CHAPTER 5 Getting down with data binding <TextBlock Text="Image:" Grid.thiesen@seb.3 Binding to a collection Binding to a collection is an important task in a lot of applications. There are numerous t Snippet 5. The Te 5.4) to a ListBox throug Result Licensed to SEB Link A/S .

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

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

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

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

to be precise).Henrik Thiesen <henrik. Result <Button x:Name="myButton" Height="70" Width="210"> <Button.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.dk> .2 Creating data templates A data template is a way to define how Table 5.11 A DataTemplate used with a ContentControl (a Button.3. which we discus Snippet 5.thiesen@seb.ContentTemplate> <DataTem Licensed to SEB Link A/S .Customizing the display 139 so you may consider using a value converter to scrub the HTML tags from a string before bin 5.

which are bound to a Licensed to SEB Link A/S . Why sho RENDERING AN ITEMSCONTROL WITH A DATATEMPLATE The ItemsControl element is designed to display a collection of items. use the binding syntax within These two points make it seem like you’re running in circles.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.Henrik Thiesen <henrik.dk> .thiesen@seb. This DataTemplate is applied t ■ C# XAML ■ When assigning your data source to the DataContext property. You may be wondering.

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

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

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 columns in a DataGrid are automat Table 5. UI virtualization mea EXPLORING BOUND COLUMNS When the AutoGenerateColumns property is set to true.thiesen@seb.dk> .Henrik Thiesen <henrik.The DataGrid 143 The DataGrid isn’t an ItemsControl The DataGrid takes advantage of a feature known as UI virtualization.

dk> . These columns can be adde Snippet 5. These columns CUSTOMIZING THE ROWS A row within a DataGrid will most likely represent a summarized view of an item.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.Colum B This snippet shows how to add columns manually to a DataGrid at design time. In these s XAML Licensed to SEB Link A/S .14 Manually adding columns to a DataGrid Result <Data:DataGrid x:Name="myDataGrid" AutoGenerateColumns="False"> <Data:DataGrid.

This property uses a DataT Licensed to SEB Link A/S .thiesen@seb. imagine adding a string property called “Keys” to the Emoticon class define Snippet 5.dk> .The DataGrid 145 how this works.15 Using the RowDetailsTemplate. 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.Henrik Thiesen <henrik.

The con VisibleWhenSelected This option will show the content in the RowDetailsTemplate for each selected row.146 Table 5.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.dk> . CUSTOMIZING THE HEADERS The DataGrid gives you the ability to customize every part of it. Th Table 5.thiesen@seb.4 Option All The options available through the DataGridHeadersVisibility enumeratio Licensed to SEB Link A/S .Henrik Thiesen <henrik. including the headers.

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

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

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

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

Henrik Thiesen <henrik.dk> .Language Integrated Query (LINQ) 151 Snippet 5. Then. 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.thiesen@seb.

thiesen@seb. the first foreach loop displays two band names B.Henrik Thiesen <henrik. What may come as a surpr Licensed to SEB Link A/S .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.dk> .

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>

1 Elements and attributes allowed in clientaccesspolicy.xml to allow HTTP access to a Table 6.1 Base clientaccesspolicy. and browser limitations 161 and the call will return as expected. 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.dk> .xml for WebClient or HTTP access <?xml version="1. security.Trust.Henrik Thiesen <henrik.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 .thiesen@seb. So.

1 CHAPTER 6 Networking and communications Elements and attributes allowed in clientaccesspolicy.162 Table 6. Snippet 6.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.Henrik Thiesen <henrik.thiesen@seb.2 More restrictive client access policy <?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allo XML Licensed to SEB Link A/S .dk> .

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

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.dk> .Henrik Thiesen <henrik. http:/ /www.microsoft.com and ASYNCHRONOUS ONLY All communication from within the Silverlight application is done asynchronously because of Licensed to SEB Link A/S .164 CHAPTER 6 Networking and communications you’re hosting your Silverlight in an authenticated application that uses tokens stored in 6.1.

a fact that can cause tr 6. If the web se 1 2 In Visual Studio 2008.Connecting to data sources 165 Note that the asynchronous behavior can occur on multiple threads.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. even using Silverlight. needs data to accomplish its 6.Henrik Thiesen <henrik.thiesen@seb.2 Connecting to data sources Nearly every application built today.2. right-click your Silverlight project and choose Add Service Referenc Licensed to SEB Link A/S .1 Using SOAP services When you think of a classic web service.

Run RECEIVING DATA WITH THE PROXY Connecting to and downloading data from a simple SOAP service is simple.thiesen@seb. You need to add tw Snippet 6.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.3 Result Calling a simple SOAP service <TextBlock x:Name="txResults" Grid.Henrik Thiesen <henrik.Column="0" Height="Auto" W XAML B C# C Licensed to SEB Link A/S .dk> .Row="0" Grid.RowSpan="2" Grid. Visual Studio also adds references to the System.

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

Anoth Licensed to SEB Link A/S .thiesen@seb.Column="0" Height="Auto" W C# XAML proxy.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.Row="0" Grid.GetCoolTextCompletedEventArgs> B } void proxy_GetCoolTextCompleted(object sender.GetCoolTextCompleted += new EventHandler<SilverService.RowSpan="2" Grid.dk> .Henrik Thiesen <henrik.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.4 Result Sending data to SOAP service <TextBlock x:Name="txResults" Grid. SilverService.

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

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

although REST may dictate the method in which a resource is acc Snippet 6.7 Getting data from a REST service private void btnSingleXml_Click(object sender. RoutedEventArgs e) { UIThread = Synchronizat B Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik.Connecting to data sources request.dk> .BeginGetResponse(SingleXmlCallBack. request). } 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.

There are three n 1 2 3 C# C Create a Uri object and initialize it with the path and. you’re making a simple request to a RESTful web service. 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. the UriKind. RoutedEventArgs e) { UIThread = SynchronizationCo C# B Licensed to SEB Link A/S . Because the default HTT Snippet 6. optionally.Henrik Thiesen <henrik.thiesen@seb.8 POSTing data to a REST service private void btnTest_Click(object sender.172 } CHAPTER 6 Networking and communications private void SingleXmlCallBack(IAsyncResult result) { HttpWebRequest request = (HttpWebRequ In this snippet.dk> .

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

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

We discussed LINQ to XML public void UpdateUiText(object stream) { XmlReader responseReader = XmlReader.Text Snippet 6. txCity.Create((Stre B C# C txtResults.10 shows the LINQ to XML version of UpdateUiText. 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.ToString().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").dk> . It shows how using LINQ to acce Licensed to SEB Link A/S . txName.Henrik Thiesen <henrik.thiesen@seb.9.

name. } .Text = hood.city.12 Using XmlSerializer public void UpdateUiText(Object stream) { XmlReader responseReader = XmlReader. public class Neighbourhood { public Licensed to SEB Link A/S .Create((Stre B C C# D txCity.Create((Stre Snippet 6.176 XMLREADER CHAPTER 6 Networking and communications It’s entirely possible to use the XmlReader itself.11 Using XmlReader public void UpdateUiText(object stream) { XmlReader responseReader = XmlReader.Text = hood. This Snippet 6.dk> . txName.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. without using a higher-level object to Snippet 6...Henrik Thiesen <henrik.thiesen@seb.

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

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

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

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

0 author RSS 2.Making the data usable 181 Table 6.dk> . This informati UNDERSTANDING THE FEED ITEMS The Items property of a SyndicationFeed object represents the collection of items in a feed Table 6.3 The properties available for a SyndicationItem Atom 1. 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.thiesen@seb.2 The main feed properties available through a SyndicationFeed.0 managingEd Property Authors Categories category category Licensed to SEB Link A/S .Henrik Thiesen <henrik.

Henrik Thiesen <henrik.3 CHAPTER 6 Networking and communications The properties available for a SyndicationItem (continued) Atom 1.thiesen@seb.17 An example RSS feed based on some blog <?xml version="1.0" encoding="utf-8" ?> <rss version="2.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. based on the fact t Snippet 6.dk> . now let’s put some of them to use USING SYNDICATEDFEED WITH RSS The RSS format allows content publishers to syndicate pure information.0"> <channel> <title>Chad Campbell XML Licensed to SEB Link A/S .182 Table 6.

dk> .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.Making the data usable <item> <title>My First Blog Post!</title> <link>http://somedomain.com/myFirstBlogPost.thiesen@seb. but it does illustrate the b Snippet 6.Henrik Thiesen <henrik.

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

20 Reading an OUT parameter WCF SL [OperationContract] string GetSomeData(int Id. out MyErrorObject myError). void serv Licensed to SEB Link A/S . Unfo Snippet 6.Using advanced services 185 6.dk> .4 Using advanced services You’ve seen how to download data and various ways to parse the returned data streams into u 6.thiesen@seb.Henrik Thiesen <henrik.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.

thiesen@seb.4.Henrik Thiesen <henrik.myError != null) { tbxMes In this snippet. you see a standard [ServiceMethod]Completed method like those shown throug 6.Error. } if (e.Error != null) { tbxMessage.186 { CHAPTER 6 Networking and communications if (e.Text = e.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.dk> .Message. let’s attach SL Licensed to SEB Link A/S .

dk> . RoutedEvent C# XML Licensed to SEB Link A/S .thiesen@seb.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. private void btnGetScores_Click(object sender.21 Snippet 6.22 Starting the process SynchronizationContext uiThread.Using advanced services 187 Snippet 6.Henrik Thiesen <henrik.

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

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

Henrik Thiesen <henrik.Current C# XML Licensed to SEB Link A/S .28 Opening TCP socket public void OpenTheSocket() { DnsEndPoint tcpEndpoint = new DnsEndPoint(Application.xml for socket access <?xml version="1.Using advanced services 191 6.dk> .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.27 clientaccesspolicy.28 Snippet 6.4.thiesen@seb.3 Connecting to sockets We’ve already discussed using a specially configured WCF service to enable push communicati Snippet 6.

28 shows the creations of an endpoint and a socket and using these to asynchronou Snippet 6. C# Licensed to SEB Link A/S . as shown in snippet 6.dk> .Henrik Thiesen <henrik.thiesen@seb. 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.192 CHAPTER 6 Networking and communications Snippet 6.30.29 Handling response public void socketArgs_Completed(object sender.

Summary 193 Snippet 6.30 Receiving message public void ReceiveMessageOverSocket(SocketAsyncEventArgs receivedArgs) { string message = When the message comes in. it needs to be converted into the correct format. a string in th 6.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 .dk> .Henrik Thiesen <henrik.thiesen@seb.

Henrik Thiesen <henrik.thiesen@seb.dk> .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 .

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

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.204 Table 7.thiesen@seb. Note that some state changes trigg Figure 7.Henrik Thiesen <henrik.1 The cycle of events as a media item plays progressively within a MediaElement Licensed to SEB Link A/S .

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

7 An example of an ASX file <ASX Version="3.206 CHAPTER 7 Managing digital media ASX files. These files can have rich. USING ASX FILES Client-side playlists are defined as Advanced Stream Redirector (ASX) files—this is just a Snippet 7.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 .Henrik Thiesen <henrik. surrounding each of the tracks.thiesen@seb.dk> . known as metadata. descriptive information.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.

2.thiesen@seb.Henrik Thiesen <henrik.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.Playlists: for that web-based mixtape Table 7. an ASX fi ACCESSING THE METADATA The metadata for a media item can be found within a read-only property called Attributes. and whe ■ Lower bandwidth costs—Generally client-side playlists serve content as separate streams for Licensed to SEB Link A/S . T 7. As you can see.2 Using server-side playlists Server-side playlists empower content administrators to dynamically determine what.dk> .

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

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

210 Table 7. In addition.thiesen@seb.dk> .2 Timely interaction The MediaElement enables you to interact with your users at specific points in time. you probably expected the ability t 7.Henrik Thiesen <henrik. This c Licensed to SEB Link A/S .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.

7 Property Text The properties associated with a TimelineMarker Description A value Time Type the majority of other collections in Silverlight.Henrik Thiesen <henrik.silverl XAML B C D This snippet shows one way you can use the MarkerReached event B.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. the metadata within the header of the file is used to create Tim Table 7. because the markers come from the media i Snippet 7.thiesen@seb.dk> . During this process. This event provides a Tim C# Licensed to SEB Link A/S .Interactive playback 211 file.

dk> . Silverlight goes fa UNDERSTANDING THE SCREEN MODES Silverlight enables you to view content in two different modes.Henrik Thiesen <henrik.2 The difference between embedded and fullscreen modes This figure shows the same Silverlight application running in the two different modes. 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. The Licensed to SEB Link A/S .3.thiesen@seb.212 CHAPTER 7 Managing digital media 7.

Using protected content 213 wise sensitive information such as bank account numbers and passwords.dk> .Host.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 .Content. Because of the sever TOGGLING BETWEEN SCREEN MODES The SilverlightHost class gives you access to the information associated with a plugin inst Snippet 7.11 Switching a plug-in into full-screen mode C# Application.IsFullScreen = true. As you probably already g 7.thiesen@seb.Current. This snippet shows how to switch a plug-in into full-screen mode.Henrik Thiesen <henrik.

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

a request mus 7.Henrik Thiesen <henrik.4.Using images in your application 215 the content is still locked (as shown in figure 7.dk> . it’s still encry 7.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 .5).5 Using images in your application Images are used on web pages all across the internet.thiesen@seb. To unlock this content.

Because this is the 7.1 Basic imaging The Image element empowers you to display images from across the internet. This Table 7. The Image in this snippet retrieves an image from the silverlightinaction.thiesen@seb.com domain.Henrik Thiesen <henrik.8 The image formats supported by the BitmapImage class. In addition to l Snippet 7.silverlightinaction.dk> .12 An Image that uses a picture from another domain Result <StackPanel Height="200" Width="100"> <Image Source="http://www.216 CHAPTER 7 Managing digital media 7.5.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 .5. These formats are inherentl This table shows the image formats supported by the BitmapImage class.

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.xml" /> This snippet shows the XAML to load a relative multiscale image at design time.Henrik Thiesen <henrik.Uri("images/dzc_output.thiesen@seb.13 Referencing a relative multiscale image in XAML XAML C# <MultiScaleImage x:Name="myMultiScaleImage" Source="images/dzc_output.Source = new DeepZoomImageTileSource( new System.14 Referencing a relative multiscale image at runtime myMultiScaleImage.x This snippet shows how to load a multiscale image at runtime. In the even Snippet 7.dk> . If the referenced image can’t Licensed to SEB Link A/S .

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

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

dk> . This region Snippet 7. As you migh Licensed to SEB Link A/S .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.16 Defining the ViewportOrigin in XAML.xml" ViewportOri This snippet shows how to set the ViewportOrigin property value at design time.

Notice the syntax of the ViewportOrigin pro void myMultiScaleImage_MouseLeftButtonUp(object sender. MouseButtonEventArgs e) { Point new This snippet shows how to reposition the ViewportOrigin based on where a user clicked.xml file and a file/folder structure.Using images in your application 221 Snippet 7. These two items m Licensed to SEB Link A/S .thiesen@seb.Henrik Thiesen <henrik. 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.dk> . Compose—Empowers you to lay out how the image These three steps will generate an .17 Defining the ViewportOrigin in C#.

Henrik Thiesen <henrik.1 I’ll have none of this stretching business Most of the time.8 The boundary of an Image element in comparison to the actual size of the photo The Image.thiesen@seb.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. Figure 7. Raster-based graphics of Licensed to SEB Link A/S . Because this technology relie 7.222 CHAPTER 7 Managing digital media Deep Zoom is a powerful feature available within Silverlight.6. photos are represented as raster-based graphics. MediaElement. and Shape (discussed in the next chapter) classes expose a propert 7.dk> .

Henrik Thiesen <henrik. the content of the element will symmetrically e Licensed to SEB Link A/S . his legs got cut off! As the result in this snippet shows.thiesen@seb.19 Use of the None option on an adequately sized Image element Unfortunately for Walker.dk> .The 7th inning stretch: Dealing with dead space 223 Snippet 7. the or 7.6.2 Uniform sizing If you set the Stretch property to Uniform.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.silverli The XAML in this snippet loads an Image and prevents it from stretching. The result from th Snippet 7.

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

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

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 .Henrik Thiesen <henrik.thiesen@seb.

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

1 CHAPTER 8 Getting a grip on graphics The Shape objects available within Silverlight. 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 .1 shows a b Snippet 8.1 Result A basic Line There are four double-precision floating-point properties (X1. you’ll learn 8. X2. Snippet 8.228 Table 8.Henrik Thiesen <henrik.1 A Line in the sand A Line is. Description A thin.1.dk> .thiesen@seb. continuous mark that co Element Line Ellipse Path Polygon Polyline Rectangle of a more general category that will be covered later in this chapter. First. obviously. a continuous line that connects two end points. Y1.

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

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

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

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

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

234 CHAPTER 8 Getting a grip on graphics Snippet 8. Segment Type LineSegment PolyLineSegment Arc XAML Licensed to SEB Link A/S . Each individual Table 8.thiesen@seb.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.dk> .2 The list of available segment types.Henrik Thiesen <henrik.

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

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

3. soothing shift between colors along Snippet 8.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 .dk> .Brushes 237 you may want something richer and more vibrant than a solid color. Thankfully.2 LinearGradientBrush The LinearGradientBrush paints an area with a gradual.Henrik Thiesen <henrik. Silverlight 8.16 A basic LinearGradientBrush rendered diagonally Result <Ellipse Stroke="Black" StrokeThickness="3" Width="64" Height="64" Canvas.thiesen@seb.

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

thiesen@seb.3.Brushes 239 8.Fill> <RadialGradientBrush> As this snippet shows.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.19 A basic RadialGradientBrush Result <Ellipse Width="75" Height="75" Stroke="Black"> <Ellipse.3 RadialGradientBrush The RadialGradientBrush is very similar to the LinearGradientBrush except that the color tr Snippet 8. This origi Snippet 8.dk> .Henrik Thiesen <henrik.

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

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

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

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

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

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

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

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

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

thiesen@seb. rotate the transformation to the 10 o’clock position. which is located on the far left si 9 With the Brush Transform tool selected. 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.Henrik Thiesen <henrik. 10 Once in the lower-left corner. your ellipse will look like this. you have something that looks much richer and vibrant. Let’s now turn our fo Licensed to SEB Link A/S . At this point. Once completed. and then change the value to White. and then change the value to Navy. 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.Blending it together 249 Click the leftmost gradient stop. At this point. 7 Click the rightmost gradient stop. Firs The Brush Transform tool is located within the toolbox.dk> . Press F5 to run the application.

Select File > Open > Project/Solution….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.Henrik Thiesen <henrik.thiesen@seb. 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. // Initialize th Licensed to SEB Link A/S .dk> . place calls to the three previously defined metho public Page() { // Required to initialize variables InitializeComponent(). within the constructor of the class.0.3 1 2 Adding event handlers to the ball in Visual Studio 3 4 Launch Microsoft Visual Studio 2008.250 CHAPTER 8 Getting a grip on graphics Walk-through 8. rotateTransform.Angle = 0.

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

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

thiesen@seb.Henrik Thiesen <henrik.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 .dk> .

Your initial conversation may 9.254 CHAPTER 9 Bringing it to life: Animation trate this value. imagine meeting someone for the first time.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 .thiesen@seb.Henrik Thiesen <henrik.dk> .

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

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

TargetName="myEllipse" Storyboard.Henrik Thiesen <henrik.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.dk> .thiesen@seb. delivering a fade effect is incredibly simple.Mastering the timeline 257 This snippet shows an Ellipse named myEllipse B.TargetProperty="Opacity" From As this snippet illustrates. 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 .

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. an animation usually has a beginning and an end.(SolidC This snippet shows an assumed Ellipse shifting from “Yellow” to “Red” over the course of on 9.thiesen@seb.1 illustrated.5 XAML XAML for shifting between colors <ColorAnimation Storyboard.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.2.TargetProperty="RenderTransformOrigin" Storyboard.Henrik Thiesen <henrik.dk> .258 CHAPTER 9 Bringing it to life: Animation Snippet 9. Licensed to SEB Link A/S .TargetName="myEllipse" Storyboard.TargetProperty="(Fill). These Snippet 9.2 Where are you starting from and where are you going? As figure 9.

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

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.10 XAML demonstrating From property within DoubleAnimation XAML <DoubleAnimation Storyboard.TargetName="myImage" Storyboard.TargetProperty="Opacity" From=" This snippet defines the animation for an assumed Image.8 shows the Opacity of the Ellipse changing from .TargetName="myEllipse" Dura Snippet 9. The To p Snippet 9.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.dk> .8 XAML XAML demonstrating the To property within DoubleAnimation <DoubleAnimation Storyboard. Note that the By property itself is Licensed to SEB Link A/S .Henrik Thiesen <henrik.TargetProperty="Opacity" Storyboard. the Opa Snippet 9.TargetProperty="Opacity" F This snippet shows the alternate to increasing a value.TargetName="myImage" Storyboard. When the animation begins. Instea Snippet 9.thiesen@seb.9 XAML XAML demonstrating By property within a DoubleAnimation <DoubleAnimation Storyboard.

By default.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 .3 How long should the animation run? As mentioned earlier. this double-pre Figure 9.dk> .1 Options for the Duration property Description Means that a Timeline will automati Property Automatic Forever Table 9.Mastering the timeline 261 how long the animation should take to get to the destination.2.2 The effects of the SpeedRatio on a Timeline with a Duration of 10 seconds.thiesen@seb. we have one final question to 9. each animation is a Timeline object.Henrik Thiesen <henrik. 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.

dk> .Henrik Thiesen <henrik.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. Licensed to SEB Link A/S .thiesen@seb.3 The effects of the RepeatBehavior on a Timeline with a Duration of 10 seconds.

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

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

<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.. <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.Storyboarding From="Green" To="Blue" /> </Storyboard> .dk> .2 Hitting the target As mentioned earlier.. the Storyboard exposes two attached properties that can be used to se Snippet 9.14 Animation overriding target of its parent Storyboard <Storyboard x:Name=“myStoryboard” Storyboard.Henrik Thiesen <henrik.3..TargetName=“myRectangle”> <ColorAnimation x:Na XAML B C D XAML E ..thiesen@seb. This target is Licensed to SEB Link A/S .

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

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

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

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

thiesen@seb. this doe Licensed to SEB Link A/S .20 Adding the EventTrigger to the collection of Triggers <Canvas.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.Loaded"> <!-. the RoutedEvent property uses a syntax that resembles elementTypeNam Snippet 9.dk> .Insert Actions here --> </EventTr As this snippet shows.Insert Actions here --> < This snippet shows how the EventTrigger has been added to a Canvas. An E Snippet 9.Loaded"> <!-.19 Defining an EventTrigger XAML XAML <EventTrigger RoutedEvent="Canvas. Significantly.Triggers> <EventTrigger RoutedEvent="Canvas.Henrik Thiesen <henrik.

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

272 CHAPTER 9 Bringing it to life: Animation Figure 9.thiesen@seb.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.dk> . This example uses two key frame XAML Licensed to SEB Link A/S .5 A bouncing ball over some variable amount of time Snippet 9.Henrik Thiesen <henrik.

6 How linear interpolation is determined Licensed to SEB Link A/S .4.dk> . The KeyFrame determines how to interpolate these values by referring to the Table 9. To understand when a 9.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.1 Interpolation: It’s about acceleration An interpolation type gives you control over how an animation will accelerate.Henrik Thiesen <henrik. The line Figure 9. or decelerat LINEAR INTERPOLATION Linear interpolation constructs the most direct transition between two key frames.Key framing 273 each KeyFrame.thiesen@seb.

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

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

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

Henrik Thiesen <henrik.dk> .5 Summary Throughout this chapter.thiesen@seb. 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.Triggers> 277 XAML B This snippet shows the typical approach for defining KeyFrame elements within an animation 9.

dk> .thiesen@seb. These featu 278 Licensed to SEB Link A/S .Henrik Thiesen <henrik.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.

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

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

3 Referencing a resource at design time.5 Retrieving the SolidColorBrush defined in snippet 10. The StaticResource Snippet 10. World" Foreground="{StaticResourc This snippet shows the basic syntax for using a resource at design time.thiesen@seb. Notice the use of the StaticResource ke XAML XAML C# <TextBlock x:Name="myTextBlock" Text="Hello.Resources["theSolidColorBrush"].dk> . World" Fore This snippet shows a valid syntactical use of a resource. if (resource != null) { Sol This snippet retrieves the SolidColorBrush defined as a resource in snippet 10.Henrik Thiesen <henrik.Being resourceful 281 Snippet 10.4. Once it’s Licensed to SEB Link A/S . 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.4 An invalid use of a resource at design time <StackPanel x:Name="myStackPanel"> <TextBlock x:Name="myTextBlock" Text="Hello.4 object resource = myStackPanel.

Henrik Thiesen <henrik. the TextBlock in snippet 10. change occurs at runtime.thiesen@seb.2 Accessing loose resources In addition to using resources defined within your XAML. When this code is executed.1.282 CHAPTER 10 Giving it style interesting.dk> . 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. If you want to access im Snippet 10.Henrik Thiesen <henrik.dk> . This g Snippet 10.thiesen@seb. demonstrating that RETRIEVING LOOSE RESOURCES WITH AN ABSOLUTE URI Silverlight gives you the flexibility to access loose resources via an absolute Uri. Thi Snippet 10.8 An absolute Uri accessing a loose resource <Image x:Name= "myImage" Source="http://www.7 A Uri accessing a relative loose resource in a subdirectory <Image x:Name="myImage" Source="directory/image02.com/image03.png" /> This snippet accesses a resource in the same directory as MySilverlightApplication. As you may have expe Licensed to SEB Link A/S . so this directory can be considered the site of origin.xap.Being resourceful 283 directory.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.png" /> This snippet shows how to access a loose resource via an absolute Uri.

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

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

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

1 Defining the look To define the look of an element using a Style.Giving your elements style <TextBox.Background> <LinearGradientBrush EndPoint="0.5.5.0"> <GradientSto 287 This snippet shows the brute-force approach to defining the visual properties of multiple e 10. you must simply set the Style property.thiesen@seb.2.Henrik Thiesen <henrik.1" StartPoint="0.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 .

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

style definitions are made up of two parts.Henrik Thiesen <henrik.15 Defining the TargetType of a Style <Grid x:Name="myGrid" Background="White"> <Grid. One part represents the name of the sty NOTE Style definitions are static. it can’t be set again.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. T Snippet 10.2.2 Targeting style definitions In CSS.thiesen@seb.dk> . There aren’t 10. once a Style is set.Resources> <Style x:Key="textStyle" TargetT B Licensed to SEB Link A/S . In Silverlight.

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. Licensed to SEB Link A/S .dk> .Henrik Thiesen <henrik. The Style in this case is configured to b 10.3 Creating templates The styling features shown in section 10.thiesen@seb.

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>

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.thiesen@seb.Leveraging the VisualStateManager Storyboard.dk> . the VisualStateManager empowers you to define a tra Snippet 10. or leaves.TargetName="myTransform" Storyboard.Henrik Thiesen <henrik. it <Button x:Name="myButton" Width="75" Height="75" Content="Push Me"> <Button.23 Creating a Button that transitions when a user hovers.Template> <Cont XAML XAML Licensed to SEB Link A/S .

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

The first VisualTransi 10.dk> .TargetProperty="ScaleY" /> </Storyboard> </V 301 e This snippet shows the definitions of two VisualTransition elements.Henrik Thiesen <henrik.24 Creating a Button that enlarges when a user hovers over it <Grid x:Name="LayoutRoot" Background="White"> <Grid.Sharing your effects Storyboard. This empowers you to d Snippet 10.thiesen@seb.Resources> <Style x:Key="buttonStyle" T Licensed to SEB Link A/S .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.TargetName="myTransform" Storyboard.

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

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

thiesen@seb.Henrik Thiesen <henrik.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 .dk> .

which clearly 305 Licensed to SEB Link A/S .dk> .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.Henrik Thiesen <henrik.thiesen@seb.

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

thiesen@seb.Henrik Thiesen <henrik. string[] noDirFound = isoFil As this snippet shows.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. you can easily retrieve both directory and file names using an absol Licensed to SEB Link A/S .2 Retrieving explicitly named files and directories string[] directory1 = isoFile.dk> .

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

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. isoFile.7 Creating a file quota bar associated with the user’s isolated storage area Result <UserControl x:Class="Chapter11.microsoft.dk> .Henrik Thiesen <henrik.CreateDirectory("Directory1").5 Creating a directory within the isolated storage area C# isoFile. In addition to creating directories at the root of the isolated storage area.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. the CreateDir Snippet 11.CreateDirectory("Directory1/SubDirectory1").thiesen@seb.6 Creating subdirectories within the isolated storage area C# isoFile.com/winfx Licensed to SEB Link A/S .CreateDirectory("Directory1 B c The first line of code B is pretty simple.

REQUESTING MORE SPACE The IsolatedStorageFile class empowers you to ask the user for more storage space.Henrik Thiesen <henrik.dk> .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.310 CHAPTER 11 Enhancing the experience Stroke="#FF000000" Canvas.Left="1" Canvas. This req Licensed to SEB Link A/S .

1.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 . from a user.8 Requesting more isolated storage space.GetUserStoreForApplication().Henrik Thiesen <henrik.dk> .thiesen@seb. more space for an application. You also hav 11. This specific dialog box asks the user Result IsolatedStorageFile isoFile = IsolatedStorageFile.Storing data in isolated storage 311 Snippet 11. long This snippet shows how to request.

9 Creating a file within a user’s isolated storage area using (IsolatedStorageFile isoFile = IsolatedStorageFile. The Table 11.dk> . 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.Henrik Thiesen <henrik.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.thiesen@seb.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 .

dk> . If the file doesn’t exist.10 Reading a file from a user’s isolated storage area.Storing data in isolated storage Table 11.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. The contents of the file using (IsolatedStorageFile isoFile = IsolatedStorageFile.thiesen@seb.GetUserStoreForApplication()) { us B C C# D As this snippet shows.Henrik Thiesen <henrik. The first ste Licensed to SEB Link A/S . a new one will be created with the gi Truncate The FileMode options shown in this table cover a wide variety of file operations. 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. reading a file is almost identical to creating a file.

At this point. we gave a quick overview of the features of XAML. T Table 11.Henrik Thiesen <henrik.2 Using XAML at runtime In chapter 1.314 CHAPTER 11 Enhancing the experience 11.dk> .thiesen@seb.1. 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. Each unique Silverlight a 11.3 Administering the isolated storage Administering an isolated storage area involves interacting with the physical filesystem.

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

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

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

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

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

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

Henrik Thiesen <henrik. Althoug 11. you define the event handler C for the RunWorkerCompleted event B.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 .WorkerReportsProgress = true.dk> . b 321 B C# C In this snippet.thiesen@seb. backgroundWorker.Retrieving content on demand backgroundWorker = new BackgroundWorker().

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

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

thiesen@seb. Rou B C D This snippet shows an event handler for an imaginary Cancel button B. protected void cancelButton_Click(object sender.Henrik Thiesen <henrik.324 CHAPTER 11 Enhancing the experience of bytes of the requested content. As this content is retrieved.21 Canceling a download request. This event handler ca Licensed to SEB Link A/S . This snippet assumes a pretend Cancel button tr WebClient webClient = new WebClient().dk> . 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.

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

when the RequestContent method is called B.com/v B C# C D } void webClient_OpenReadCompleted(object sender.dk> .thiesen@seb. This web ser LOADING MEDIA CONTENT As you saw in chapter 7.326 CHAPTER 11 Enhancing the experience This snippet uses a WebClient to call a web service that returns data in JSON.Henrik Thiesen <henrik. media is an important part of the modern web.silverlightinaction.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. This met Licensed to SEB Link A/S . This important piece Snippet 11. on demand.

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

com/f B C# } void webClient_OpenReadCompleted(object sender.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().Henrik Thiesen <henrik. 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.dk> .thiesen@seb.silverlightinaction. Licensed to SEB Link A/S .25 Loading an image from a compressed package that was retrieved on demand private void RequestContent() { Uri address = new Uri("http://www.

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

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

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

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

thiesen@seb. C# (Statically typed language) public class Bird { public Licensed to SEB Link A/S .5 Duck typing in action.dk> .Henrik Thiesen <henrik.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.

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

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

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

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

thiesen@seb.dk> . It’s been a 338 Licensed to SEB Link A/S .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.Henrik Thiesen <henrik.

Creating a user control 339 creating a user control will be covered in section 12. Licensed to SEB Link A/S .1 Creating a user control Because Silverlight is still in its infancy. 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. Behavior.1.1 Defining the appearance Defining the appearance of a UserControl involves creating the XAML for the user interface.Henrik Thiesen <henrik.dk> . a 12.1.thiesen@seb. A user control can be used as a pa 12.

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

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

Register( " B C# Licensed to SEB Link A/S . In addition.thiesen@seb.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.3 Registering a DependencyProperty with the dependency system public static readonly DependencyProperty IsLockedProperty = DependencyProperty.Henrik Thiesen <henrik.342 CHAPTER 12 Share the light: Distribution and deployment a DependencyProperty.dk> . 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.

thiesen@seb.Henrik Thiesen <henrik. 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. new PropertyMetadata(new PropertyChangedCallback(OnIsLockedChanged 343 C# C This snippet shows how to register a property as a DependencyProperty. This s Snippet 12.Creating a user control typeof(LockableTextBox).2 The properties of the DependencyPropertyChangedEventArgs structure Description T Property NewValue OldValue Property This table shows the properties of the DependencyPropertyChangedEventArgs structure. DependencyPropertyChangedEventArg This snippet shows the event handler for the PropertyChangedCallback delegate specified in C# Licensed to SEB Link A/S .dk> .4 Registering a DependencyProperty with the dependency system private static void OnIsLockedChanged(DependencyObject o.

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

microsoft.2.xaml file <UserControl x:Class="Chapter12. 12.6 The XAML of the NavigationService.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> . Figure 12.Henrik Thiesen <henrik.1 Setting up the architecture Architecting your Silverlight application to provide navigation is fairly straightforward. the details will be loaded and displayed in a page called Details.com/winf B Licensed to SEB Link A/S .Architecting navigation in Silverlight 345 items is selected.NavigationService" xmlns="http://schemas.xaml.thiesen@seb.

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

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

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

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

11 The createObjectEx function call that associates a splash screen with Silverl <div id="parent1"> <script type="text/javascript"> Silverlight.350 CHAPTER 12 Share the light: Distribution and deployment This snippet defines a basic animation within a Canvas element.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 .3.Henrik Thiesen <henrik.thiesen@seb.dk> . Y Snippet 12.2 Integrating the custom splash screen The second step of using a custom splash screen is integrating it with a web application. This animation rotates an E 12.

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

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

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

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

com/invoke/7867/ My%20Silverlight%20App/ifram This snippet shows how to reference a Silverlight application hosted within Silverlight Str 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.thiesen@seb.Summary 355 an authentication service to prevent any funny business.microsof Licensed to SEB Link A/S .Henrik Thiesen <henrik.dk> .5 Summary Throughout this chapter.services. Although they’re extremely valuabl Snippet 12.live.15 Referencing a hosted Silverlight application JavaScript 1 <iframe src="http://silverlight.

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

thiesen@seb. 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 .index Symbols .NET Framework 7.dk> .NET 200 framework 306 .Henrik Thiesen <henrik.

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

243 CornerRadius property 121 cost effective med CaptureMouse method 94 Cascading Style Sheets.dk> . 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 .thiesen@seb.Henrik Thiesen <henrik.INDEX 359 corner lower-right 237 upper-left 237.

dk> .Henrik Thiesen <henrik.thiesen@seb. 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.

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. state-based 298 element tree 86 ElementToLo Expression Blend 8. 303.xap 282. 245. 257 feed items 181 FileDialogFileInfo 120 FileMode 312 files . 277. Licensed to SEB Link A/S .Henrik Thiesen <henrik.dk> .thiesen@seb. 316 Brushes property editor 17 Objects and Timeli F fade animation 255. 13–21.

65.thiesen@seb. 229. Alexey 3 Gecko 25 Generator property 181 geometries c GetStyleAttribute 47 GetStylusPoints method 123 GetTop method 58 GetUserStoreForApplication Height property 16. 332 Gavrilov.Henrik Thiesen <henrik. 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 .dk> .362 fonts (continues) Trebuchet 73 TrueType 73 Verdana 73 FontSize animation 257 pixels ver INDEX G garbage collection 167.

See LINQ Language property 181 Licensed to SEB Link A/S .dk> .thiesen@seb. 340 animating the Opacity property 254 animation 259 data binding 134 pixelation IO. 89 calling from managed code 51. See filesystem IQueryable 154 IronPython 332–333 IronRuby 332 IsBusy property 324 IsChe J JavaScript 2.Henrik Thiesen <henrik.INDEX 363 Image 216. 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.

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

340.Henrik Thiesen <henrik. 121 Page. 329.xaml 14 Panel 294.dk> . strongly typed 177 Offset property 237 Licensed to SEB Link A/S . 345 animation 257 Pa O OBJECT tag 31 Objects and Timeline panel 19 objects. 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.INDEX 365 PlayReady 213 installation 214 server SDK 215 plug-in. 331 OpenText method 120 Op P packaged XAML 30 Padding property 79.

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.thiesen@seb. 247. 25 safeguards full-screen mode restriction 213 limits to user input 213 ScaleTran Licensed to SEB Link A/S . 349 RadioButton 102 grouping 103 RadiusX property 239 RadiusY Rectangle 12.Henrik Thiesen <henrik. 16.dk> . 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.

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

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

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

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. 284.thiesen@seb. Licensed to SEB Link A/S . See WCF Window X W W3C 24 Wait cursor 81 wax file 205 WCF 185 duplex services 186 web property 23 web server.370 URI 167. 197 destination 171 relative 283 Uri 101.Henrik Thiesen <henrik. 322. 327 absolute 283 relative INDEX V Value attribute 288 property 116.dk> .

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

Sign up to vote on this title
UsefulNot useful