Silverlight 4 Unleashed 0672333361, 9780672333368


276 87 39MB

English Pages 736 Year 2010

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

Silverlight 4 Unleashed
 0672333361, 9780672333368

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Laurent Bugnion

Silve rligh t ™

zyxwvutsrqponmlkjihgfedcbaZYXWVU

4

I UN LEASH ED

8 0 0 East 9 6 t h St reet , Indianapolis, Indiana 4 6 2 4 0 USA

Si l verl i ght ™ 4 Unleashed

Ed i t o r -i n -Ch i ef zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Ka r e n Ge t t m a n

Co p yr i gh t © 2 0 1 1 by Pe ar so n Ed u cat i o n All r i gh t s r e se r v e d . No p ar t of t h i s b o o k sh al l b e r ep r o d u ced , st o r e d In a r et r ieval sy st e m , or t r an sm i t t e d by an y m e a n s, el ect r o n i c, m e ch an i cal , p h o t o co p yi n g, r eco r d i n g, or o t h er w i se, w it h o u t w r it t en p e r m i ssi o n f r o m t h e p u b lish er . No p at en t liabilit y Is a ssu m e d w it h r e sp e ct t o t h e u se of t h e In f o r m at i o n co n t ai n e d h er ei n . Al t h o u gh ever y p r ecau t i o n h a s b e e n t ak e n In t h e p r ep ar at i o n of t h i s b o o k, t h e p u b l i sh er an d au t h o r

Exe cu t i ve Ed i t o r N e i l Ro w e

De ve l o p m e n t Ed i t o r M a r k Re n f r o w

a ssu m e no r esp o n si b i l i t y f or er r o r s or o m i ssi o n s. Nor Is an y liabilit y a ssu m e d f or d a m a g e s r esu l t i n g f r o m t h e u se of t h e In f o r m at i o n co n t ai n e d h er ei n .

M a n a g i n g Ed i t o r

I SBN - 1 3 : 9 7 8 - 0 - 6 7 2 - 3 3 3 3 6 - 8

Kr i st y H a r t

I SBN - 1 0 : 0 - 6 7 2 - 3 3 3 3 6 - 1

Pr o j ect Ed i t o r Li b r ar y of Co n g r e ss Cat al o gi n g-l n -Pu b l l cat i o n Dat a

A n d y B e a st e r

Bu gn l o n , Lau r en t .

Co p y Ed i t o r

Si l ver l i gh t 4 u n l e a sh e d / Lau r en t Bu gn i o n .

Ke i t h Cl i n e

p. cm . I n cl u d e s In d ex.

I n d e xe r

I SBN 9 7 8 - 0 - 6 7 2 - 3 3 3 3 6 - 1 1.

Si l ver l i gh t (El ect r o n i c r e so u r ce ) 2 .

M u l t i m ed i a sy st e m s. 3. Ap p l i cat i o n so f t w ar e —

Dev el o p m en t . 4. W eb si t e d evel o p m en t . 5 . (Co m p u t er sy st e m s)

In t er n et p r o gr am m i n g. 6 .

User In t er f aces

I. Tit le.

Br a d H e r r i m a n

Pr o o f r e a d e r Je n n i f e r Ga l l a n t

Q A 7 6 . 5 7 5 . B8 3 9 2 0 1 1 006.7' 6— d c22

Te ch n i ca l Ed i t o r 2010040175

Pe t e r Br o m b e r g

Pr i n t ed In t h e Un it ed St a t e s o n Am e r i ca

Pu b l i sh i n g

Fi r st Pr in t in g Oct o b er 2 0 1 0

Co o r d i n a t o r

Tradem ark s

Ci n d y Te e t e r s

All t e r m s m en t i o n ed In t h i s b o o k t h at ar e kn o w n t o b e t r a d e m a r k s or se r v i ce m a r k s h ave b e e n ap p r o p r i at el y cap i t al i zed . Sa m s Pu b l i sh i n g can n o t at t est t o t h e accu r acy of

B o o k De si g n e r

t h i s In f o r m at i o n . U se of a t er m In t h i s b o o k sh o u l d not b e r egar d ed a s af f ect i n g t h e

Ga r y A d a i r

val i d i t y of an y t r ad e m ar k or se r v i ce m ar k .

Co m p o s i t i o n

Warning and Disclaim er

Gl o r i a Sc h u r i c k

Ever y ef f o r t h a s b e e n m ad e t o m ak e t h i s b o o k a s co m p l e t e an d a s accu r at e a s p o ssi b l e, but no w ar r an t y or f i t n e ss Is i m p l i ed . Th e In f o r m at i o n p r o vi d ed Is o n an " a s i s" b a si s. Th e au t h o r an d t h e p u b l i sh er sh al l h ave n eit h er liabilit y nor r esp o n si b i l i t y t o an y p e r so n or ent it y w it h r e sp e ct t o an y l o ss or d a m a g e s ar i si n g f r o m t h e In f o r m at i o n co n t ai n e d In t h i s b o o k or f r o m t h e u se of t h e p r o gr am s acco m p an y i n g It .

Bulk Sales Sa m s Pu b l i sh i n g o f f er s excel l en t d i sco u n t s o n t h i s b o o k w h en o r d er ed In q u an t i t y f o r b u l k p u r ch a se s or sp e ci a l sa l e s. For m o r e In f o r m at i o n , p l e ase co n t act

U.S. Corp ora t e a nd Gove rnm e nt Sa le s 1 -8 0 0 -3 8 2 -3 4 1 9 corp sa le s@p e a rson t e ch grou p .com For sa l e s o u t si d e of t h e U . S. , p l e ase co n t act

I nt e rna t iona l Sa le s int e rna t iona l@pe a rsone d.com

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJ

Conte nts at a Gla nce

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF

Foreword

xxiii

Introduction

1

1

Three Years of Silverlight

7

2

Setting Up and Discovering Your Environment

27

3

Extending Your Application w ith Controls

49

4

Investigating Existing Controls

75

5

Understanding Dependency Properties

103

6

Working w ith Data: Binding, Grouping, Sorting, and Filtering

129

7

Understanding the Model-View-ViewModel Pattern

157

8

Using Data Controls

187

9

Connecting to the Web

215

10

Creating Resources, Styles, and Templates

247

11

Mastering Expression Blend

273

12

Sketching User Experience

301

13

Creating Line-of-Business Applications

329

14

Enhancing Line-of-Business Applications and Running Out of the Browser

15

365

Developing Navigation Applications and Silverlight for Windows Phone 7

401

16

Using Effects and Recording Media

435

17

New Transforms, Right Click, HTML Browser, WebBrowserBrush, and Isolated Storage

18

Drag and Drop, Full Screen, Clipboard, COM Interop, Duplex Polling, Notification Windows, and Splash Screens

19

467 503

A uthentication, Event to Co mmand Binding, Random A nimations, Multitouch, Local Co mmunicatio n, and Bing Maps Control

539

Building Extensible and Maintainable Applications

573

21

Optimizing Performance

609

22

Advanced Development Techniques

641

Conclusion

675

Index

677

20

Table of Conte nts

Foreword

1

xxiii

Introduction

1

Three Years of Silverlight

7

Discovering Silverlight 4

7

Learning Silverlight Is Betting on the Future

8

How Can They Be So Fast?

9

How A bout Co mpatibility w ith Older Versions? Cross-Brow ser and Cross-Platform Co mpatibility

9 10

Windo w s and Macinto sh

11

Linux

12

A lternatives to Silverlight

12

In the Web Browser

12

Out of the Browser

13

Legacy Techno lo gies A Sho rt History of Silverlight

14 15

Silverlight 1.0

16

Silverlight 2

16

Silverlight 3

16

A nd Silverlight 4

17

Preview ing the Future of Silverlight

17

Installing Silverlight 4 as a User

18

Opening a Silverlight 4 A pplication W hat to Do If Silverlight Is Not Installed? Exploring Silverlight 4 Demo s Deep Z o o ming the Matterho rn

19 19 19 19

Getting Involved Socially w ith Sobees

20

Navigating w ith Bing Maps Streetside and Pho to Synth

21

Visualizing Info rmatio n w ith the Pivot Viewer

23

Draw ing on the Web w ith Fantasia

25

How Can You Get Involved?

25

Summary

26

Co n t e n t s

2

Se tting Up and Discovering Your Environm ent

Installing Visual Studio

27 27

Visual Web Developer Express

28

Installing the Silverlight Tools for Visual Studio

28

Verifying the Installatio n

29

Inspecting the A pplication

31

Unpacking an XAP File

32

Using the Visual Studio Designer

32 33

Checking the Properties Editor

34

Adding So me Text

36

Using Design Time Wid th and Height

39

Saving the A pplication

40

Installing Expression Blend

40

Creating a New Silverlight A pplication

40

Opening Hello Silverlight

41

Adding an Effect

42

Creating a Pulse A nimatio n

44

Triggering the Storyboard

45

Testing the A pplication

46

Summary

47

Extending Your Applica tion with Controls

49

Extending XAML

49

Mapping a Prefix to a CLR Namespace

49

W hy Is a Prefix Not Always Needed?

52

Adding a Namespace to Any Element

52

Defining Your Own URI and Mapping CLR Namespaces W hat's a Co ntro l?

4

27

Visual Studio 2010

Implementing Hello Silverlight

3

v

52 53

User Co ntro ls

53

Custo m Co ntro ls

63

Summary

73

Investiga ting Existing Controls

75

Review ing the Basics

75

Show Me So me Code!

76

Changes in Existing Co ntro ls

77

Mouse W heel Support

77

Localizing for Right-to-Left Languages

77

Getting a Co ntro l Template's Current State

78

zyxwvutsrqponm

vi

Si l v e r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Adding zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Se l e c t e dVa l ue and Se l e c t e dVa l ue Pa t h 79 Adding Comma nd and Comma ndPa r a me t e r

79

Presenting and Editing Text w ith the Ri c hTe xt Box

84

Z o o ming w ith the Vi e wbox

85

Opening a Chi l dWi ndow

87

Finding More Info rmatio n

90

W here to Find A dditional Co ntro ls?

90

Do You Really Need a Co ntro l?

90

The Silverlight Toolkit

91

Installing the Silverlight Toolkit Third-Party Providers

5

Summary

102

Understa nding Dependency Properties

103

Inheriting De pe nde nc yObj ect

104

Threading

104

A ccessing a Depend ency Property's Value

105

Using a De pe nde nc yObj ect as Data Item

105

Registering Depend ency Properties Defining Metadata Initializing Depend ency Objects Understanding A ttached Properties

108 109 Ill 114

Using A ttached Properties for Values

114

Registering an A ttached Property

115

Using Custo m A ttached Properties in XAML

118

Implementing an A ttached Behavior

118

Building on A ttached Behaviors w ith Blend Behaviors Adding a New Property w ith Snippets

122 123

Installing the Snippets for Silverlight

123

Using the Snippets

124

Calculating a Depend ency Property's Value Getting the Property's Base Value Reading the Local Value

6

92 101

124 126 126

Summary

127

W orking with Da ta : Binding, Grouping, Sorting, and Filtering

129

Diving into Data Bindings

130

Understanding a Binding's Elements

130

Understanding the Namescope

132

Setting the Source

133

Refining the Path

136

Co n t e n t s

vii

Flow ing in Two Directio ns

138

Co nverting the Values

138

Changing the Format

139

Handling Special Cases

141

Property Trigger

142

Validating Input

142

Using the Visual Studio Binding Dialog

zyxwvutsrqponm

146

Using the Expression Blend Binding Dialog

148

Debugging Data Bindings

149

Checking the Output Tab

149

Creating a Test Converter

150

Grouping, Filtering, and Sorting Data

151

Working w ith thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Col l e c t i onVi e wSour c e 151

7

Using a Pa ge dCol l e c t i onVi e w

154

Binding Directly to the Source

154

Summary

155

Understa nding the M odel-View-ViewM odel Pa ttern

157

A bout Design Patterns

157

Separating the Co ncerns

158

W hy Is Separation Go o d?

158

Classic Separation Patterns

158

History of MVVM

159

Developing Expression Blend

160

Presentatio n Model for WPF and Silverlight

160

A rchitecture of MVVM Translating to Silverlight Two Kinds of View -models Binding the View to the View -model

160 161 162 163

Understanding the Data Co ntext

163

Inheriting the Data Co ntext

164

Binding to the View

164

Building a Sample A pplication

168

The Model's Interface

168

Building a Cus t ome r Vi e wMode l

170

Calling the Service in the Ma i nVi e wMode l

172

Binding to Results

174

Testing the A pplication

177

Bridging the Separation Implementing a Vi e wMode l Ba s e Class

178 178

Using Co mmand s

180

Sending Messages

183

viii

Si l v e r l i g h t 4

8

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Using an MVVM Framew ork

184

W hat Could Be Better?

184

Summary

184

Using Data Controls

187

Filtering and Paging w ith thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Pa ge dCol l e c t i onVi e w 188 Preparing the Sample

190

Filtering Data

192

Paging Thro ugh Data

194

Optimizing Data Handling

195

Implementing Custo m Sorting

195

Adding a Da t a Pa ge r Co ntro l Custo mizing the Display Validating Data Input

196 197 197

Using Interface-Based Validation

198

Validating w ith Data A nno tatio ns

201

Validating Before or After the Data Is Set

203

Validating on the Client and on the Server

203

Review ing the Da t a Gr i d

204

Using the Da t a Gr i d w ith A uto matic Co lumns

204

Cho o sing Betw een Da t a Gr i d and Li s t Box

208

Editing Data in the Da t a For m

9

188

Building the Pa ge dCol l e c t i onVi e w

208

Adding a Description

210

Validating the Input

211

Co mmitting Changes Manually

211

Defining Fields Manually

212

Getting More Info rmatio n

213

Making a Simple Property Editor

213

Summary

214

Conne cting to the W eb

215

Getting Info rmatio n fro m Cross-Domain Servers

216

Checking W hether a Policy File Exists

216

Working A round Cross-Domain Restrictions

217

Placing Simple Calls

218

Info rming the User

218

Learning w ith a Sample

219

Do w nlo ading Strings

219

Detecting Errors, Checking the Result

223

Opening a Resource for Reading

224

Uploading a String

225

Co n t e n t s

Opening a Resource for Writing A ccessing Headers Sending Co mplex Messages

ix

zyxwvutsrqponm

227 231 231

Posting a File to the Server w ithzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDC Ht t pWe bRe que s t 231 Discovering the New Netw orking Stack

234

Using the Client HTTP Stack

235

Using Other HTTP Metho d s

236

Using the Cooki e Cont a i ne r Handling Responses Handling XML Responses

238

Handling JSON Responses

238

Co mmunicating w ith WCF

239

Setting Up a Service

239

Co nnecting the Client A pplication

241

Updating the Code on the Server

244

Publishing the Service

10

236 237

244

Summary

245

Crea ting Resources, Style s, and Tem plates

247

Working w ith Resources in XAML

248

Using Local Resources

248

Merging Dictio naries

249

From the Same A ssembly

250

From a Different A ssembly

251

Resolving Resources

254

Working w ith Resources in Blend

256

Merging a Resource Dictio nary

256

Creating New Resources

257

Selecting a Resource for a Property

257

Using the Resources Panel

257

Cleaning Up Unused Resources Using the Pistachio Tool Styling a Co ntro l

259 259 260

Using Implicit Styles

261

Creating a Hierarchy of Styles

263

Creating a New Style in Blend Templating a Co ntro l

264 265

Copying a Template in Blend

265

Creating a Custo m Easing Functio n

269

Making a Co ntro l in Blend

270

Applying a Theme

271

Summary

272

x

Si l v e r l i g h t 4

11

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

M a stering Expression Blend

273

W hat Is Blend, Exactly?

274

Working as a Tool for Integrators

274

Editing XAML Markup

274

W hen Sho uld You Use User Co ntro ls? Making an A pplication Blend W hy Is So me Code Not Executed?

275

W hy Does So me Code Fail?

275

Detecting the Cause of an Exceptio n

276

Isolating Code in Design Mode

278

Creating Design Time Data in Blend

280

Understanding the Design-Time Data Co ntext

288

Using Blend Behaviors

12

274 275

289

Behavior, Trigger, or A ction?

292

Adding a Blend Behavior in Code

293

Creating a New Blend Behavior

293

Finding More Info rmatio n

300

Summary

300

Sk etching User Experience

301

Sketching as a Discovery Process

301

Using Sketching and Wireframing Tools

302

Other Kinds of Sketching

303

Discovering SketchFlow

304

Creating a New SketchFlow A pplication

305

Checking the Panels

305

Creating and Co nnecting Screens

305

Building the UI Creating a Co mp o nent Screen

308 309

Using Sketch Co ntro ls

310

Exploring the Sketch Co ntro ls

313

Creating States and Transitions

318

Building an A nimatio n

321

Deploying the SketchFlow A pplication

323

Running the Prototype

323

Giving Feedback

324

Impo rting and Managing User Feedback

325

Impo rting and Exporting

325

Impo rting from Pho to sho p and Illustrator

326

Impo rting from Pow erPoint

326

Exporting to Word

326

Co n t e n t s

Integrating and Co llabo rating

13

327

Integrating into SharePo int

327

Integrating into Team Fo undatio n Server

327

Summary

328

Crea ting Line-of-Business Applica tions

329

Preparing the Server-Side

331

Prerequisites

332

Preparing the Server-Side A pplication

332

Creating the Silverlight Client

333

Bringing the Client and the Server Together

334

Adding a Do main Service

334

Inspecting the Do main Service Class

335

Inspecting the Metadata

336

Creating a New Server-Side Query Working w ith the Visual Designer

336 338

Understanding the Do mainDataSo urce

339

Calling a Query w ith Parameter

339

Sorting the Data

341

Adding a Pager

341

Refactoring the A pplication to MVVM

342

Adding a View -model

342

A dapting the XAML Markup

345

Custo mizing the Co lumns

346

Localizing the User Interface

347

Adding a RelayCo mmand Class

348

Executing the CRUD Operatio ns in Code

348

Displaying Messages fro m the View -model

351

Deleting an Order

354

Validating the Values

357

Filtering the Data

360

Show ing Feedback W hile Processing

362

Sharing Code

363

Summary 14

xi

363

Enha ncing Line-of-Business Applica tions and Running Out of the Browser

365

Enhancing LOB A pplications

365

Adding Paging

365

Show ing Errors

369

Reco nciling Data

371

Copying and Pasting Rows

373

Printing

373

zyxwvutsrqponm

xii

Si l v e r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Taking Silverlight Out of the Browser

382

Setting Up the A pplication

383

Uninstalling the A pplication

384

Debugging the OOB A pplication

385

Looking Under the Hood

386

Changing the Settings

387

Updating the A pplication

391

Installing fro m the Code

393

Saving Files

395

Working Offline Summary 15

398 399

Developing Navigation Applica tions and Silverlight for W indows Phone 7

401

Navigating w ith Silverlight

401

Sho uld You Always Use a Navigation A pplication?

404

Creating a New Navigation A pplication

404

A ccessing Navigation Info rmatio n

412

Providing Custo m Navigation

413

Adding Navigation to a Non-Navigation A pplication Developing w ith Silverlight for Window s Pho ne 7

414 415

Getting Hardware

416

Targeting a Specific A udience

416

Developing for Windo w s Pho ne 7

416

Developing for a Unifo rm Hardware Platform

417

Designing for the Pho ne

418

Installing the Tools

419

Selling Your A pplications

420

Building Co mpatible A pplications for the Desktop and the Pho ne Co ntinuing the Explo ratio n

16

420 432

Summary

432

Using Effects and Recording M edia

435

Creating Effects w ith Pixel Shaders

435

Writing, Finding, and Co mpiling Shader Files

436

Creating and Modifying Shaders w ith Shazzam

437

Integrating Shaders in the A pplication

438

Adding Properties and A nimating Shaders

440

Using Shaders for Transitions in the VSM

443

Co n t e n t s

A ccessing the Webcam and the Micro p ho ne

xiii

443

Getting the List of Devices

444

Enabling Access

448

Displaying the Video Output

448

Detecting W hether Other A pplications Use the Device

449

Capturing Audio Co nverting to a WAV File

450 450

Creating a Sink

450

Using the SaveFileDialog

452

Using the Sink and Adding Co mmand s

454

Wiring the Co mmand s

456

Testing Audio Recording Writing to a Bitmap

457 457

Saving the Picture to a PNG File

459

Manipulating Pixels

460

Extending WriteableBitmap

462

Using the Open File Dialog

464

Learning About News in Media

465

Summary

466

New Transform s, Right Click , HTM L Browser, W ebBrowserBrush, and Isola ted Stora ge

467

Transforming Elements in a Pro jectio n

467

Setting A dditional Properties

469

Using a Matrix3DPro jectio n

470

A nimating the PlanePro jectio n

470

Co mpo sing Transforms

472

Handling the Right-Click Event

473

Handling a Routed Event

473

Displaying a Co ntext Menu Hosting an HTML Browser (Out-of-the-Brow ser Only) Understanding the Limitatio ns

476 478 479

Building a Simple Web Browser

480

Loading HTML Co ntent from Memo ry

484

Invo king JavaScript

485

Writing and Reading in the Isolated Storage Saving to the Isolated Storage

485 485

Reading fro m the Isolated Storage

492

Deleting Files

495

Using the IsolatedStorageSettings

496

Trusting the Isolated Storage or Not

499

Painting w ith HTML

499

Summary

501

zyxwvutsrqponml

xiv

Si l v e r l i g h t 4

18

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Drag and Drop, Full Screen, Clipboa rd, COM Interop, Duplex Polling, Notifica tion W indows, and Spla sh Screens

503

Dragging and Dropping

503

Dragging Files o n the Silverlight A pplication

504

Drag-and-Drop Restrictions

505

Working in Full Screen

507

Getting Keyboard Support in Full-Screen Mode (Elevated Permissions) Using Full Screen on a Mo nito r W hile Working on A no ther Copying to and from the Clipboard

510

Working w ith COM (Elevated Permissions)

512

Understanding the Restrictions

512

Co mmunicating w ith Micro so ft Office

512

Co mmunicating over Duplex Polling

19

507 509

519

Implementing the Server-Side Service

519

Unregistering a Client

524

Co nfiguring the Service

524

Implementing the Client

525

Unsubscribing and Resubscribing

528

Testing the A pplication

529

Displaying No tificatio n Windo w s

530

Understanding the Restrictions

530

Adding a No tificatio n Wind o w

531

Queuing No tificatio n Windo w s

533

Interacting w ith the Main Windo w

533

Creating a Custo m Splash Screen

534

Summary

537

Authentica tion, Event t o Com m and Binding, Random Anim a tions, M ultitouch, Loca l Com m unica tion, and Bing M a ps Control

539

Logging In w ith A uthenticatio n

539

Creating a New Website

540

Adding and Managing Users

541

Co nfiguring the A uthenticatio n Web Service

542

Checking the Access

544

Adding References to the Services

544

Implementing the Client

545

Binding an Event to a Co mmand Executing a Co mmand W hen a TextBo x Loses Focus Building Random A nimatio ns

547 548 554

Creating the Base A nimatio n in Blend

554

Rando mizing the A nimatio n

555

Co n t e n t s

Implementing Multito uch in Silverlight

558

Investigating Existing Elements

559

Using Multito uch Libraries

560

Scaling, Rotating, and Translating

560

Implementing a Multito uch A pplication

561

Using Multito uch in Window s Pho ne 7 A pplications

563

Finding More Info rmatio n

563

Enabling Local Co mmunicatio n

563

Understanding the Restrictions

564

Building a Receiver

564

Building a Sender

565

Testing the A pplication

567 567

Adding the Map

568

Getting Lo catio n Info rmatio n and Marking It

569

Getting More Info rmatio n

571

Summary

571

Building Extensible and M aintainable Applica tions

573

Inverting Dependencies w ith Unity

zyxwvutsrqponm

557

Getting the Right Co mputer

Mapping w ith the Bing Maps Co ntro l

20

xv

573

Refactoring to Smaller and Simpler Classes

575

Setting Up the Services

578

Calling thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Se t up Metho d and Wiring Up 582 Discovering More A bout Unity Co mpo sing an A pplication w ith MEF Exporting and Impo rting

584

Do w nlo ading on Demand

594

W hat A bout Prism?

603

Using an MVVM Framew ork Discovering the Co mp o nents Sending Messages

21

583 583

604 604 604

Summary

607

Optim izing Perform ance

609

Improving the XAP Do w nlo ad Time

609

Loading Co ntent on Demand

611

Caching Co mmo n A ssemblies

615

Virtualizing the User Interface

616

Virtualizing the I t e ms Cont r ol

617

Unvirtualizing the ListBox

619

Simplifying the DataTemplate

619

xvi

Si l v e r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Creating Items in Batches

620

Working in Threads

621

A ccelerating the User Interface

624

Enabling Hardware A cceleration in the Browser

624

Enabling Hardware A cceleration Out of the Browser

628

A ccelerating w ith Care

629

A ccelerating in the Window s Pho ne 7

630

Using a Code Profiler

630

Avoiding Memo ry Leaks

631

Saving an Object on the Stack or the Heap

631

Co llecting Garbage and Leaking Memo ry

632

Living a Shorter Life

635

Unregistering Event Handlers

635

Disposing Objects

637

Using Weak References

637

Finding a Leak

22

638

Summary

639

Adva nced Developm ent Techniques

641

Using New C# and .NET Features

641

Using Modern Programming Syntax

641

Creating Extensio n Metho d s

645

Co nsuming Dynamic Objects

646

Using Named/ Optional Parameters Localizing A pplications

646 647

Adding a Resource File

647

Making an A pplication Localizable

648

Using Tools

651

Do w nlo ading Resource A pplications on Demand

652

Encrypting and Decrypting Understanding the Encryption/ Decryption Mechanism Multithreading

652 652 653

W hat Is a Thread?

653

Using the ThreadPool

654

Dispatching Back to the UI Thread

657

Creating and Using azyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Ba c kgr oundWor ke r 660 Locking Critical Resources

663

Enhancing Multithreaded Code

666

Unit Testing the A pplication

667

Installing a Unit Test Framew ork

668

Adding Functio nality w ith TDD

668

Co n t e n t s

xvii

Using Code Coverage

673

Unit Testing Windo w s Pho ne 7 A pplications

673

Summary

674

Conclusion

675

Index

677

zyxwvutsrqponmlk

About the Author

zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCB

Laurent BugnionzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA works as a senior user-experience integrator for IdentityMine, one of the leading companies co mmitted to redefining the user experience and a Microsoft Gold Partner dedicated to easing the adoption and optimal use of Microsoft presentation technologies, including Window s Presentation Foundation (WPF), Silverlight, Window s Phone 7, Surface, and Window s 7.

Originally an electronics engineer, Laurent achieved postgrad credentials in software engineering in 1999. Before IdentityMine, he worked for Siemens for 13 years, introducing WPF and other .NET 3.5 technologies worldwide. His responsibilities involved developing w ith the previously mentio ned technologies, training and coaching his colleagues, coordinating and integrating the graphic-design work, and fostering relationships w ith Microsoft. Before that, he wrote embedded C/ C++, and then moved to desktop computers in Java, JavaScript, and eventually .NET (desktop and ASP.NET). Privately, he codes in Silverlight, WPF, and ASP.NET. He blogs onhttp:/ / blog.galasoft.ch and writes on http:/ / www.galasoft.ch, where he publishes articles, prototypes, and demos related to the previously mentio ned technologies. In 2008, he earned an MCTS for WPF. (In October of that same year, his bookzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed was published.) This year, 2010, is his fourth year as a Microsoft MVP (Silverlight), and he was selected this year as Silverlight MVP of the year. Laurent is based in Zurich, Switzerland, where he lives w ith his wife, Chi Meei, and his two daughters, Alise and Laeticia.

Dedica tion

zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA

Thank you Chi Meei for not killing me when I said I wanted to write a new book. Thank you for supporting me during the 11 months that it took. I love you. To my princesses Alise and Laeticia for bringing light in my life, and for making me keep things in perspective. I love you both so much. To my parents and my grandparents, for helping me become who I am today. Imagination is more important than knowledge. xwvutsrqpnmliecbaSPMJEBA — Albert Einstein

Il nous faut écouter L'oiseau au fond des bois Le murmure de l'été Le sang qui monte en soi Les berceuses des mères Les prières des enfants Et le bruit de la terre Qui s'endort doucement. — Jacques Brel

Ack nowledgm ents zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB Thanking everyone w ho helped me complete this book would probably take another 700 pages. So, to keep these acknow ledgments concise, I w ant to generally thank everyone w ho helped in any way, w hile specifically calling out a few w ithout w hom I couldn't have completed this work. The Silverlight co mmunity has been no thing short of fantastic. I received w onderful motivation every time I was about to throw in the towel (usually around 2 a.m.). I found documentation about the most cryptic topics in amazingly rich and detailed blog posts, and I had the best reviewers in the world, w ho did all that work w ith just the promise of a "thank yo u" and a beer next time I meet them. It is a wonderful time to develop software. I especially w ant thank the follow ing (in no particular order) and apologize to those I might have forgotten: zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA At IdentityM ine: Nathan Dunlap, Jo sh Wagoner, Jo sh Smith, Andrew Whidett, and Jo nathan Russ for teaching me all I know (or so it feels); Lu Silverstein, Mark Brown, Chad Brown, and Craig Jaris for encouraging me to write this book and dealing w ith the disturbance.

The designer dream team: Jo nah Sterling, Javier Roca Garcia, Jamey Baumgardt, Stuart Mayhew, Lydia Bagwell, and more w ho help me to think differently. And all the others for making me part of the family. It is a privilege to work w ith you. M y dream team of reviewers: Corrado Cavalli, Laurent Kempe, David Gardner, Peter Bromberg, David Anson, Jo sh Smith, Shawn Wildermuth, Christian Schormann, Colin Blair, Tim Heuer, Rene Schulte, Walt Ritscher, and Glenn Block. Thank you so much.

A very special extra thank you to Laurent Kempe and Corrado Cavalli for jumping in at the last minute to review additional chapters. At M icrosoft: For building these fantastic frameworks and tools, and for answering my frequent pleas for help: Scott Guthrie, Ian Ellison-Taylor, Tim Sneath, Nikhil Kothari, Jo hn Gossman, Jaime Rodriguez, Laurence Moroney, Jesse Liberty, Jo hn Papa, Rob Relyea, Ted Hu, Stefano Malle, Ronnie Saurenmann, Sascha Corti, Pete Brown, Jeff Wilcox, David Anson, Christian Schormann, Pete Blois, Unni Ravindranathan, Kirupa Chinnathambi, Jo anna Mason, David Teitlebaum, Tim Heuer, Glenn Block, Karen Corby, Mike Harsh, Jo e Stegman, Rochelle Benavides, Grant Hinkson, Katrien de Graeve, Lisa Feigenbaum, Mark Boulter, Chad Royal, Chris Koenig, and all the others at the DevDiv. The source of eternal inspiration and support: Dave Campbell, Adam Kinney, Robby Ingebretsen, Kevin Moore, Charles Petzold, Marlon Grech and all the WPF disciples, Shawn Wildermuth, Walt Ritscher, Justin Angel, Davide Zordan, David Yack, Don Burnett,

Erik Mork, Brian Noyes, Ward Bell, Rob Eisenberg, Dan Wahlin, Chad Campbell, Jo hn Stockton, Jo nas Follesoe, Seema Ramchandani, Brian Henderson, Ian Smith, Scott Barnes, Jeremy Likness, Page Brooks, Rick Barraza, Cigdem Patlak, Michael Sync, Victor Gaudioso, David Kelley, Anand Iyer, all the Silverlight MVPs, and the w hole vibrant and amazing Silverlight community. zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA The great team at Sams: And especially Neil Rowe (my editor, mentor, and friend since 2007), Andy Beaster, and Mark Renfrow.

We Want t o Hear from You!

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPON

As the reader of this book,zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA you are our most important critic and commentator. We value your opinion and w ant to know w hat we're doing right, w hat we could do better, w hat areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can email or write me directly to let me know w hat you did or didn't like about this book—as well as w hat we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and pho ne or email address. I will carefully review your co mments and share them w ith the author and editors w ho worked on the book. Email:

[email protected]

Mail:

Neil Rowe Executive Editor Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA

Rea der Se rvice s Visit our website and register this book at informit.com/ register for co nvenient access to any updates, downloads, or errata that might be available for this book.

Foreword zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA The growth of Silverlight has been perhaps faster than any of us involved in its inception would have predicted. In less than three years, Microsoft has released four desktop releases, each packing a payload of hundreds of features in response to customer feedback. Silverlight is now deployed on somewhere approaching tw o-thirds of all Internetco nnected PCs,1 and it's the primary platform for general-purpose development on the new Windows Phone 7. Silverlight powers all manner of mainstream applications: from high-end media experiences like Netflix, NBC Sports, and Sky Player to the web version of Office. It's in use at top consumer websites like eBay and for mission-critical applications inside the firewall of numerous Fortune 500 companies. In one sense, Silverlight is, of course, just an evolution of the .NET Framework that has been central to Microsoft's developer strategy for the past ten years. It stands on the shoulders of giants like Window s Presentation Foundation (WPF,) the big-sister techno logy that preceded it and laid the groundwork—with an architecture and XAML format that had already proved itself in real-world implementations. When we started building Silverlight, one of the greatest constraints was size. We knew we needed something that was lightw eight and easy to deploy w ithout requiring a big download or dependencies on other prerequisites. At the same time, we w anted to ship a high-quality product as quickly as possible. There was a lot of debate internally about w hether we should start w ith the existing .NET codebase and "take away" code or w hether we should "build up" by starting w ith a clean slate and gradually adding features until we had an attractive product. In the end, we w ent w ith the latter approach, and I think it shows in the final product: Silverlight contains the key things that a developer needs w hile bringing little cruft along for the ride. For me, this is one key reason w hy Silverlight offers a unique sweet spot of power, flexibility, and easy deployment that suits it well for bo th consumer and business usage. But a framework alone isn't sufficient for most pragmatic developers, w ho are less interested in history lessons or arcane details of internal architecture and more concerned w ith w hat they themselves can create quickly and efficiently. Over the last year or two since the lastzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight Unleashed book was published, it's true that Silverlight has been expanded and enhanced; but even more important, the palette of tools available to a Silverlight developer has grown tremendously. In particular, the release of Visual Studio 2010 brought true WYSIWYG in-place editing to Silverlight, along w ith WCF RIA Services, a set of classes and design-time tools that offer majo r productivity gains to business application authors. Beyond the core elements of Silverlight, a burgeoning co mmunity has sprung up over the past couple of years bo th inside and outside of Microsoft. The engineering team themselves have released a plethora of open source controls, components, and themes along w ith rich frameworks for media, extensibility, and analytics. Others have contributed libraries and co mpo nents for everything from PDF creation to physics engines and full 3D

xxiv

Si l v e r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

support: CodePlex alone shows nearly 500 projects that are based on Silverlight. And of course, there is an endless supply of great co ntent targeted at Silverlight developers, including the weekly Silverlight TV show at http:/ / silverlight.tv. What of the future of Silverlight? Some have argued that the rapid rise of HTML5 presents a new competitive threat to Silverlight. It's certainly true that the browser wars of old are back, w ith vendors duking it out to deliver the most advanced hardware-accelerated graphics platform for developers while delivering a stable and secure browser for a broader audience. It's also true that HTML in general has the most pervasive reach of any client platform. Indeed, the mo mentum behind Internet Explorer 9 shows that we at Microsoft are also putting a lot of energy into providing first-class support for "standards-based" web development.

A favorite business read among Microsoft executives iszyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFE Built to Last by Jim Collins and Jerry Porras, w hich highlights how easy it is to be trapped by a false dicho to my (the "tyranny of the 'OR'"). The authors no te how many strategic decisions are framed incorrectly as a choice betw een A or B (but not bo th). Yet often the correct answer is an and rather than an or. In this vein, there need be no fork in the road betw een HTML5 and Silverlight. Both serve key needs that developers have, and bo th have powerful strengths. Even more important, many so-called Silverlight applications are in fact hybrid solutions that combine bo th technologies. Silverlight contains many useful bridging features to enable developers of bo th hues to access code and UIs w ritten in the opposite framework. Silverlight developers should therefore feel confident that their skills have value for the indefinite future and that Silverlight itself has a rosy future. I w ant to close this foreword by no ting my delight to see this update to Laurent's popular predecessor title, Silverlight 2 Unleashed. I've had the privilege of know ing Laurent for some years now, and I can tell you that few in the Silverlight co mmunity co mmand the respect that he does. He combines a passion for writing quality client software w ith a deep, practical, real-world knowledge of the tools and framework. He has had an insider's view of each release of Silverlight as it has been developed, and his feedback has shaped the product for the better. Laurent's own experience developing complex, large-scale Silverlight applications shines through, particularly in the more advanced topics toward the end of the book. I heartily co mmend this book, bo th to new comers to Silverlight as well as to those w ho already have experience w ith early releases of Silverlight and w ant to "upgrade" their knowledge w ith the latest advances. zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA — Tim Sneath Senior Director, Client Platform Evangelism M icrosoft Corp. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

1

attested by our internal data and sites like riastats.com, which measure A syxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB based on millions of real-world

users.

deployments

of plug-ins

Introduction

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Silv erlig ht 4, released to the public in April 2010, represents a majo r forw ard step in the histo ry of this still-young techno lo gy. A ltho ugh w e'll certainly see later versions of the framew ork w ith additio nal features in the future, the current version is very mature and easy to work w ith. In addition, the to o ls used to develop Silverlight have also grow n and offer the same level of maturity and ease of use.

It is interesting to take a good lo o k at the extended Silverlight co mmunity today. From a niche topic, Silverlight has beco me the source of many discussions on Tw itter and various blogs. Also, since days of Silverlight 2, we have w itnessed the emergence ofzyxwvutsrqponmlkjihgfedcbaXWVUTS design patterns and of po lished external framew orks. It is no w possible to talk to Silverlight experts w ho have developed many professional applications, and w ho kno w w hat w orks best. The bo o k yo u have in your hand s (or on your computer/ e-reader/ tablet/ phone screen) tries to describe the current version of Silverlight version 4) as fully as possible. Doing so represents a difficult task, how ever, because of the multiple facets of this techno lo gy and the number of pro blems it can solve. You w ill find that this bo o k goes into much mo re detail than Silverlight 2 Unleashed. That increased level of detail is intentio nal, and in fact, this bo o k builds on the fo und atio n presented in that earlier publicatio n.

Honing Your Ba sic Sk ills Silverlight is very much a story of co ntinuity betw een versions. Mo st changes are in fact additional features. For developers w ho were already active in earlier versions of Silverlight, the skills that yo u already ow n are going to help yo u advance in Silverlight 4. For developers w ho are co mpletely new to Silverlight, we provide a free co py (as a PDF dow nload) of Silverlight 2 Unleashed. This bo o k was w ritten w ith beginners in mind , and w ill bring yo u up to speed w ith fund amental co ncepts such as XAML, basic co ntro ls, transforms, animatio ns, and more.

W ha t Ca n You Lea rn from vtsrnmlkihgedcaVUSRNMKEA Silverlight 2 Unleashed? The follow ing chapters in Silverlight 2 Unleashed w ill help yo u to understand the basics of Silverlight 4:

If you are already experienced with Silverlight

2 or Silverlight 3 , feel free to sk ip t his st ep • Chapter 1, "Intro d ucing and jum p right into Chapter 1. Silverlight," explains w here Silverlight co mes fro m. A lthough the landscape of web techno lo gies evolved in tw o years, mo st of the info rmatio n in this chapter is still very much valid. Note, how ever, that mo st demos described in Chapter 1 are no t current anymo re. In some cases, yo u w ill get errors, or the page w ill simply no t be fo und anymo re. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

2

Si l v e r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

• Chapter 2, "Understanding XA ML," is still valid. You can learn a lot about the fundamentals of XAML by reading this chapter. • Chapter 3, "Playing w ith XAML Transforms and A nimations," is still valid. All the transforms and animations present in Silverlight 2 work unchanged in Silverlight 4. • Chapter 4, "Expression Blend," refers to Expression Blend 2. Many basic features are still valid, but we will cover Expression Blend 4 in this book. • Chapter 5, "Using Media," is still valid and describes colors, vector graphics, and basic image and video handling. • Chapter 6, "Blending a Little Mo re," is still an interesting read, and provides an overview of functionalities that are still available in Expression Blend 4 (transforms, opacity masks, paths, clipping paths, grouping controls, and making user controls). • Chapter 7, "Deploying to a Web Page," is still valid w ith minor changes. It shows you how to select a provider for your website and how to deploy your Silverlight application to that site. • Chapter 8, "Programming Silverlight w ith JavaScript," is less relevant to Silverlight 4 than it was to Silverlight 2. However, JavaScript is an important skill to have for anyone w ho is involved into creating web applications. • Chapter 9, "Understanding .NET," and Chapter 10, "Progressing w ith .NET," provide a tutorial from scratch about the most important constructs of the C# programming language and of the .NET framework. It is a good read for people w ho come to Silverlight from Flash, for instance, and have never worked in .NET before. • Chapter 11, "Progressing w ith A nimations" is still valid and will teach you how to create animations in Blend, how to start and stop animations in code, and other special kinds of animations. Silverlight 4 and especially Blend 4 build on this and offer additional features that you will discover in the present book. • Chapter 12, "Encoding Videos w ith Expression Encoder," and Chapter 13, "Progressing w ith Videos," are based on Expression Encoder 2. The current version of this software (Expression Encoder 4) available today offers much of the same functionalities, w ith added features and a slightly different look and feel. Note, however, that the Microsoft Silverlight Streaming servers are unfortunately no t available anymore. • Chapter 14, "Letting Silverlight and JavaScript Talk," is less relevant to Silverlight 4, although most of the techniques will still work. • Chapter 15, "Digging into Silverlight Elements," and Chapter 16, "Digging Deeper into Silverlight Elements," are still very much current. In fact, it is almost a mustread before starting to work in Silverlight. • Chapter 17, "Using Resources, Styling, and Templating," is still valid; however, it is possible to store resources in external resource dictionaries in Silverlight 4, w hich was no t the case in Silverlight 2.

Int roduct ion

3

zyxwvutsrqponm

• Chapter 18, "Data Binding and Using Data Controls," will be developed deeper in zyxwvutsrqponmlkjihgfed Silverlight 4 Unleashed. The section about the DataGrid is still an interesting read if you are working w ith this control. Note, however, that the DataGrid is now part of the core Silverlight framework. • Chapter 19, "Creating User Controls and Custom Co ntro ls," overlaps in part w ith the present book's co ntent. Controls are a very important part of the Silverlight framework, and it is important to understand how they are built and how they work. • Chapter 20, "Taking Silverlight 2 One Step Further," and Chapter 21, "Taking Silverlight 2 Even Further," lists various topics, some of them overlapping w ith the present book's co ntent. • Chapter 22, "Co nnecting to the Web," overlaps in part w ith the present book's co ntent, but also has some interesting techniques to download files and access their co ntent. • Chapter 23, "Placing Cross-Domain Requests and Handling Exceptions," contains information about the topic of cross-domain co mmunicatio n that is still current in Silverlight 4, as well as a tutorial about exceptions and how to handle them.

• Chapter 24, "Silverlight: Continuing the Jo urney," contains various information that can be interesting for Silverlight developers. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJI

About Code in This Book We tried to keep formatting as consistent as possible throughout this book and to make the code look like it does in Visual Studio. The source code is color-coded to help you to work faster and so that you can recognize key concepts in Visual Studio and in Expression Blend. Note that depending on the co ntext where a keyword is used (XAML or C#, Visual Studio, or Expression Blend), the color code might differ. The source code lines are numbered only where relevant (for example, w hen the text makes explicit reference to a line number). The w hole source code for this book is available online at http:/ / www.galasoft.ch/ SL4U/ code. A translation of the C# code into VB.NET is being prepared at the time of this writing.

Adding a Reference to a Na m e spa ce In some listings, classes from other namespaces/ assemblies are added to the code. In some occasions, doing so might cause a compilation error w ith the follow ing message: The type or namespace name 'MyClass' could not be found (are you missing a using directive or an assembly reference? ).

4

Si l ve r l i g h t 4

Un l e a s h e d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

To correct this, make sure that the assembly in w hichzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED MyCl as s is defined is added to the References folder in the Visual Studio So lutio n Explorer. If that is no t the case, right-click this folder and select Add Reference fro m the co ntext menu. In the Add Reference dialog, brow se to the missing assembly and add it to the pro ject. If the error persists, yo u must add a reference to the namespace in w hich MyCl as s is placed in the source code file. You can do so by adding an entry at the to p the current page, as follow s (w here Si l ve r l i ght Appl i c a t i onl . Anot he r Na me s pa c e is the namespace in w hich MyCl as s lives): us i ng

Si l v e r l i g h t Ap p l i c a t i o n l . An o t h e r Na me s p a c e ;

In Visual Studio, this step can be auto mated by placing the cursor inside the name MyCl as s and pressing Ctrl+. (Ctrl and a dot) to o pen the co ntext menu. Then, select the first entry of the menu to add a us i ng directive. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

Se t t ing the Right Proje ct a s St a rt up W hen an existing solution is opened, and this so lutio n co ntains a web pro ject ho sting the Silverlight applicatio n (in the ClientBin folder), the w eb pro ject sho uld be set as Startup. This means that w hen Ctrl+F5 is pressed in Visual Studio, the Silverlight applicatio n w ill be executed in ht t p : co ntext, and no t in the f i l e : co ntext that has mo re restrictions. To ensure that the web pro ject is set as Startup, follow these steps: 1. Check in the So lutio n Explorer w hether the w eb pro ject is represented in bo ld. If that is the case, skip to Step 3. 2. If that is no t the case, right-click the w eb pro ject's name and select Set as StartUp

Pro ject fro m the co ntext menu. 3. Right-click the HTML test page name (usually named [YourSilverlightA pplicationjTestPage.html or ind ex.html) and select Set as Start Page fro m the co ntext menu.

Using the zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA v an Keyword Since Silverlight 3, it has been possible to use the var keyw ord to implicitly type a local variable. For example, in the follow ing code, bo th expressions are exactly similar after the code is co mpiled: va r myVa r i a bl e l

= ne w But t on( ) ;

But t on my Va r i a b l e 2 = ne w But t on( ) ;

There is a lo t of discussion in the .NET co mmunity abo ut the usage of the var keyw ord. Cho o sing to use the keyw ord or no t is very much a matter of personal preference, and there is unfo rtunately no w ay to please everyone in this matter. In this bo o k, the var keyw ord is used co nsistently as show n here.

Int roduct ion

Happy Coding!

5

zyxwvutsrqponm

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Now it's time to start! I wish you a successful journey in this book, and I am anxious to hear from you on Twitter (@LBugnion). I canno t promise to reply to every message, but I will definitely do my best, and I am very open to criticism (as long as it is constructive) and questions. Enjo y the trip, and happy coding! Laurent Stafa, Switzerland, September 2010

This page intentionally left blank

CH A P TER

1

Three Years o f Silverlight

I n three short years, Silverlight has co me a very lo ng way. In this chapter, we review w hat Silverlight is, w here it co mes from, and try to peek into the future of this techno logy, illustrated by the "shiny lo go " show n in Figure 1.1.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML I N TH I S CH A P TER , W E W I LL: •

Discuss wha t happened since Silverlight 2 Unlea shed cam e out.



Talk about cross-browser and cross-pla tform com pa tibility for Silverlight 4 .



Consider a lterna tives to Silverlight, both in the browser and out-of-thebrowser.



Look at the earlier versions of Silverlight 1 .0 , 2 and 3 and ta k e a look into the future of this technology.



Install Silverlight 4 as a user

Discove ring Silve rlight 4

It seems like yesterday that we published zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 and explore a few dem os. zyxwvutsrqponmlkjihgfedc Unleashed and intro duced it at the Professional Developer Co nference 2008 in Los A ngeles just a few days after Silverlight 2 had been released to the Web. A nd yet here we are talking abo ut Silverlight 4 already! In these less than tw o years, the Silverlight team at Micro so ft has been very active listening to the co mmunity's feedback and implementing new features to transfo rm w hat was an already solid, yet basic platfo rm into a very rich framew ork, able to acco mmo d ate mo st client applicatio n developers' needs.

8

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

The very first public glimpse of Silverlight 4 beta was offered at the Professional Developer Co nference 2009, w hen Sco tt Guthrie (Corporate Vice President, .NET Developer Platform, Micro so ft) gave o ne of the exciting talks full of demos for w hich he is famous. A lthough still in beta stage, we were already able to clearly see the direction that the techno lo gy was taking. Even mo re impo rtant, we were to ld o ften that Silverlight is the future of client applicatio ns at Micro so ft!

W ith this new release, the border betw een web applicatio ns and desktop applicatio ns is beco ming much thinner. For FIGURE 1 .1 example, Silverlight 4 can no w install applicatio ns "o ut of the Silverlight logo. zyxwvutsrqponmlkjihgfedcbaZ bro w ser," w ith a sho rtcut in the Start menu or on the desktop. A ltho ugh these applicatio ns have fewer privileges and features than full-blow n desktop applications, they have the W h a t Ab o u t W i n d o w s P re se n t a t i o n huge advantage to be cross-platform Fou n d a t i on ? (you can run them on Apple computers, The richer (but running on Windows only) "big to o ) and provide a very elegant w ay to sist er" of Silverlight called Windows offer rich functio nality in o nline and Presentation Foundation (WPF) is still actively also o ffline mo d e. We talk a lot mo re developed and extended by Microsoft, abo ut out-of-the-brow ser applicatio ns in although in a m aybe less-glam orous way. See this bo o k. the sect ion "Alternatives to Silverlight," later in this chapter.

A lo t of o ther features, w hich we discuss later to o , help the developers to build so-called line-of-business (LOB) applicatio ns (for example, rich data applicatio ns for businesses, catalogs for products, data visualization screens, and many more). Silverlight is o ften mistaken for yet ano ther media framew ork, w hen it is in fact much mo re than this. This new release makes the p o int very clear, and sho uld help to put Silverlight in the fo cus of enterprise applicatio ns developers w hile co ntinuing to build on the success it already has for multimed ia applications.

Lea rning Silve rlight Is Be t t ing on the Future W ith all this in mind, it is quite clear that learning Silverlight is a perfect w ay to advance in the future of client application develo pment: • For w eb developers, it adds impo rtant skills to your arsenal that w ill help enrich your web pages. Silverlight is no t replacing classic w eb techno lo gies such as Hypertext Markup Language (HTML), Cascading Style Sheets (CSS), and JavaScript, but it enhances them and plays an impo rtant role in the w ay that w ebsites are evolving always mo re fro m d o cument presentatio n to rich interactive applications.

D i s c o v e r i n g Si l v e r l i g h t 4

9

zyxwvutsrqponm

• For "classic" desktop developers in the Window s w orld (w ith techno lo gies such as Micro so ft Fo undatio n Classes [MFC] or Windo w s Forms), it teaches yo u a mo dern and exciting framew ork w ith revo lutio nary features such as the fantastic data bind ing system, rich animatio ns and graphics, media integratio n, and so on. • For WPF developers, yo u leverage a lo t fro m w hat yo u already know and gain crossplatfo rm co mpatibility for your applications, easy web deplo yment, and exposure to a wider audience.

One impo rtant thing to keep in mind is that Silverlight is no t a replacement for HTML web pages, and w ill abso lutely no t kill HTML. Silverlight is here to enhance your w eb pages w ith richer co ntent, and w ith the out-of-the-brow ser feature, to create lightw eight applicatio ns that can functio n o nline or o ffline. Learning Silverlight does no t mean that yo u should avoid w riting HTML code, or that yo u sho uld stop investing in techno lo gies such as ASP.NET. But it means that yo u can no w realize applicatio ns that were impossible (or very difficult) to do in HTML/ CSS/ JavaScript, and that yo u can use the same languages (and in some cases reuse code) o n the server and on the client. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO

How Ca n The y Be So Fa st? There are a few aspects that explain ho w new versions of Silverlight can hit the market so fast, and yet be so stable: • Silverlight is developed in an agile manner. W ith short iteratio ns and early releases, the team is able to react quickly w hen pro blems are fo und in the code or new features are suggested. This explains w hy we had three releases in less than three years. • Silverlight is taking advantage of the experience gathered by the Window s Presentatio n Fo undatio n team. Many features are similar, and some code can even be reused. Other features are re-implemented in a different w ay based o n custo mer feedback. The teams are co mmunicating to leverage the experience gained since WPF was released. Th e Co m m u n i t y Co u n t s!

• The co mmunity is invo lved in an interactive manner. Your input co unts! We w ill talk about ways to get invo lved in this chapter.

Did you know that approxim ately 70% of the features requested by the Silverlight com m unity have been im plem ented in Silverlight 4!

How About Com pa t ibilit y wit h Older Ve rsions? An agile team at work for Silverlight provides a great basis for a rich feature set evolving very fast. W ith version 4, we can say that Silverlight is reaching maturity. There will, of course, be additional versions in the future, but it is obvious that versions 3 and 4 were

10

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

majo r steps for this platform, w hich explains Microsoft's enthusiasm at the conferences where early versions were show n. Note, however, that a lot of effort has been put into backward compatibility: • If you open a Silverlight 2 (or 3) project in the Silverlight 4 development environment, a lot of your code will work as is. Some of it will need to be updated, but the changes are, in general, painless ones. Note that the project files (*.CSPROJ) will be updated to the new environment, though. • If you run a Silverlight 2 (or 3) application on a PC w ith Silverlight 4 installed, it will run w ithout glitches, because the runtime environment is fully backward compatible.

In fact, your Silverlight 2 (or 3) applications should run even better in a Silverlight 4 runtime environment, because of the improvements brought to the core and to the plugin. This history of backward compatibility is most certainly going to continue w ith future versions, so w hat you learn now is going to be a major skill for your future as a developer. zyxwvutsrqponmlkjihgf

Cross-Browse r and Cross-Pla tform Com pa tibility The version of Silverlight developed by Microsoft is available on a wide variety of platforms, bo th on the Windows and Macintosh operating systems. This plug-in will run on all these platforms w ith the same feature set (with one exception that we will discuss in Chapter 18, "Drag and Drop, Full Screen, Clipboard, COM Interop, Duplex Polling, Notification Windows, and Splash Screens," namely the COM integration that is of course available only on Windows operating systems). In addition, Novell is working on a version named Moonlight, available for certain distributions of Linux. The effort by Novell is encouraged by Microsoft but is conducted independently. This is w hy the version releases are no t necessarily coordinated, and there might be some discrepancies in the feature set, to o . However, a great effort is being expended to create a plug-in that is largely compatible w ith the one developed by Microsoft. Finally, we will also take a look in Chapter 15, "Developing Navigation Applications and Silverlight for Windows Phone 7" at Silverlight for the mobile platform. After announcing that they w anted to support the mobile platform, Microsoft did no t communicate much and encountered a few technical difficulties that took longer than expected to solve. This year, however, we finally heard much more about support for the mobile platform, and we will take a first look at w hat will be available in the near future. In short, Silverlight is your best bet if you w ant to run .NET-based code on a large number of platforms!

Cross-Brow ser and Cross-Plat f orm Com pat ibilit y

11

zyxwvutsrqponmlkjihgf

W indows and M a cint osh zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA The follow ing table show s in detail w hat is and is no t possible w ith the plug-in implemented by Micro so ft.

TI P Th i n gs Are M o vi n g Fa st

Table 1.1 is a snapshot at the tim e of t his writing. The situation keeps changing, with new browsers and platform s being added. To get the latest inform ation, make sure to visit the Silverlight.net website!

v

/

TABLE 1 .1

1

Cross-Platform and -Browser Com patibility

OS

IE8

IE7

IE6

FF3

Safari3

Safari4

Chrom e

Windows 7

Yes

Yes

n/ a

Yes

n/ a

n/ a

Yes

Windows Vist a

Yes

Yes

n/ a

Yes

n/ a

n/ a

Yes

Windows Server 2008

Yes

Yes

n/ a

Yes

n/ a

n/ a

Yes

Windows Server 2 0 0 8 R2

Yes

n/ a

n/ a

n/ a

n/ a

n/ a

Yes

Windows XP SP2 and SP3

Yes

Yes

Yes

Yes

n/ a

n/ a

Yes

Windows 2000 SP4 1

n/ a

n/ a

Yes

n/ a

n/ a

n/ a

n/ a

Windows Server 2003

Yes

Yes

Yes

Yes

n/ a

n/ a

n/ a

Mac OS 1 0 .4 .8 and later (Intel based)

n/ a

n/ a

n/ a

Yes

Yes

Yes

Yes yxwvutsrqponmlkjihgfedcbaW

Windows 2000 requires the installation

of an update (KB 891861) to execute Silverlight

applications.

Note the follow ing restrictions: • The Opera w eb brow ser is no t officially supported at the time of this w riting. • Pow erPC-based Apple co mputers support o nly Silverlight 1.0.

12

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

Linux zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA For Linux, FreeBSD, and Solaris operating systems, things are changing fast, so the best thing to do is to check the info rmatio n o n the Novell Mo o nlight w ebsite at http:/ / w w w .galasoft.ch/ sl4-moonlight.

Alt e rna t ive s to Silve rlight Because Silverlight 4 can run inside or outside of the w eb browser, its alternatives cover a wider landscape. Interestingly, tho ugh, no t many techno lo gies allow yo u to program just o nce but run o n multiple platforms and in multiple mo des (offline/ online, in the browser/ out of the brow ser). In that sense, Silverlight is pretty unique.

In the W eb Browse r Silverlight is traditio nally a co nnected applicatio n running w ithin a web browser. In that field, the landscape didn't really change much since Silverlight 2, w ith the exceptio n maybe of XHTML, w hich is barely mentio ned anymo re and co nsidered already o bso lete no w that HTML5 is beco ming a trending to pic. Adobe Fla sh

This is the obvious co ntender, the o ne techno lo gy that is mo st o ften mentio ned w hen Silverlight is co mpared to o ther framew orks. Adobe Flash is installed o n a huge number of co mputers and various operating systems. It is also a w ell-kno w n enviro nment, and many co mpanies develop applicatio ns in Flash for the Web. As mentio ned w hen Silverlight 2 was released, Flash is no t going to be killed by Silverlight, and in fact this was never Micro so ft's intentio n. Rather, Silverlight provides a w elco med alternative to firms w ho do no t w ant to invest in tw o very different techno lo gies for the desktop and the Web. In that sense, Silverlight is a great cho ice because it is developed w ith the same languages and the same tools as the w ell-know n Window s Forms, ASP.NET, and WPF. Silverlight and Flash are co existing on the Web, so metimes even in the same w eb pages. Thankfully, this is easy to realize, and there is even a possibility to let these mixed applicatio ns co mmunicate to gether thro ugh JavaScript. This allows a gradual mo d ificatio n of existing w ebsites fro m Flash to Silverlight, w itho ut breaking the functio nalities or forcing the users to adapt to large-scale changes. We actually saw some striking examples of this at Micro so ft itself, w ith existing Flash applicatio ns being gradually co nverted to Silverlight w itho ut disruptions. D HTM L a nd AJAX

DHTML (Dynamic HTML) and AJAX (A synchronous JavaScript and XML) are o ften used to gether on w eb pages to create a mo re interactive experience. This was made popular w ith w eb developers by the release of JavaScript framew orks such as j Query.

A l t e r n a t i v e s t o Si l v e r l i g h t

13

zyxwvutsrqponml

The advantage of these framew orks is that they standardize the JavaScript functio ns by providing a layer on to p of Usi n g j Qu e r y in ASP . N ET the various imp lementatio ns available in Did you know that Microsoft support s jQuery different w eb brow sers o n different platdevelopm ent by contributing to t his open forms. j Query can be extended by plugsource project, and including it in ASPNET ins that are available for the user MVC (Model, View, Controller) projects in experience itself (for example, to create Visual Studio, v / smo o ther animatio ns), or at a low er level to enhance the co mmunicatio n w ith the web server, and so o n. Also, they do no t require an additional co mp o nent in the w eb brow ser to run. However, pro gramming in JavaScript is no t an easy task. The d ynamic nature of the language makes it mo re difficult to offer advanced d evelo pment tools (such as IntelliSense in Visual Studio) and to find and correct bugs. Also, the HTML platfo rm is limited: A dvanced and smo o th animatio ns w ith high frame rates are impossible to realize, it is impossible to create certain transfo rmatio ns for graphic elements, and so fo rth. Note, how ever, that using Silverlight o n a web page do esn't prevent yo u fro m using j Query or ano ther JavaScript-based framew ork—on the contrary. Here, to o , these techno lo gies co mp lement each other. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA HTM L5

This new revision of HTML intend s to provide a wide range of rich functio nality, allow ing developers to reduce the use of third-party plug-ins. In this matter, it po sitio ns itself as a co ncurrent of Adobe Flash and Micro so ft Silverlight. A lthough it is true that plug-ins cause problems, they also solve some. One big issue w ith HTML is that different web brow sers have different imp lementatio ns of the standard. This is a w ell-know n issue: Testing a web page for all majo r web brow sers on all majo r operating systems can be a real hassle. On the o ther hand, Silverlight as a plug-in is guaranteed to run the same in every supported web browser. It is the old "w rite o nce, run anyw here." The majo r issue that HTML5 faces is that a wide ado ptio n w ill take a lo t of time. Also, if we learned anything fro m the past, it is that each brow ser is likely to offer a slightly different feature set. So me features w ill simply be missing fro m some brow sers; o ther features w ill be imp lemented in a different manner. Co mpatibility w ill take a lo t of time, if it is ever achieved. In the meantime, and until we kno w w hether HTML5 really delivers w hat it promises, Silverlight offers a real alternative.

Out of the Browse r Running a Silverlight applicatio n out of the brow ser is similar to running a desktop applicatio n. Therefore, Silverlight can be seen as an alternative to any desktop techno lo gy, including "classic" MFC and Window s Forms applicatio ns on Window s or Mac applicatio ns o n Mac OS. Let's just take a lo o k at tw o mo dern desktop techno lo gies.

14

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

W indow s Pre se nt a t ion Founda tion

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

W hen Silverlight functio nalities are no t eno ugh to acco mplish w hat yo u w ant, the answer is pro bably to lo o k into WPF, Silverlight's "big sister." Even tho ugh the co nvergence is always greater betw een these tw o techno lo gies, and Silverlight beco mes richer and steps o n WPF's playground, there are still some scenarios for w hich Silverlight is no t suitable.

TI P D e p loyin g W P F on t h e W e b

Did you know that WPF applications can be deployed and installed from a web server using the ClickOnce technology? See http:/ / www.galasoft.ch/ sl4 -click once. Also, a WPF application can be deployed and run inside som e web browsers on Windows, and provide an interesting alternative to Silverlight. See http:/ / www.galasoft.ch/ sl4 -xbap.

The biggest disadvantage of WPF w ith regard to Silverlight is that it runs o nly on Windo w s systems. Also, it requires the co mplete .NET framew ork (instead of the Silverlight subset), w hich is larger and takes mo re time to install o n the target machine if it is no t already present. Finally, altho ugh WPF is richer than Silverlight, this richness also makes it mo re co mplicated to learn. It is easier to start w ith Silverlight. Note that thanks to the co mbined efforts of the Silverlight team and the WPF team at Microsoft, the co mpatibility betw een bo th techno lo gies has never been greater, and it is in fact possible to co nvert a Silverlight applicatio n to WPF w ith a large po rtio n of shared code. Generally speaking, how ever, and because Silverlight is a subset of .NET, it is easier to start in Silverlight and extend the applicatio n to WPF than the co ntrary. Similarly, it is also easier to start learning Silverlight and then to mo ve to WPF. Adobe AI R

A less w ell-kno w n platfo rm developed by Adobe is called AIR and allow s creating desktop applicatio ns. As such, it is no t a co ncurrent of "in-bro w ser" Silverlight, but rather of the out-of-the-brow ser applications. For users, AIR applicatio ns are kno w n to be heavy in memo ry co nsumptio n, and require an additional framew ork that must be installed the first time yo u run an AIR applicatio n (even if yo u have Flash already installed). This can be a problem on corporate netw orks, w here IT departments are o ften reluctant to install new co mp o nents o n users' PCs. Silverlight, on the o ther hand, is installed o nce and gets the out-of-the-brow ser capabilities immediately.

Le ga cy Te chnologie s So me techno lo gies are still running inside some web brow sers, but are beco ming o bso lete w ith time. The tw o mentio ned in this section are no t the o nly ones, but they are the best kno w n, and it is possible that a developer starting a new pro ject w ill be asked to consider these in the variant analysis.

A S h o r t H i s t o r y o f Si l v e r l i g h t

Ja va Apple t s

15

zyxwvutsrqponm

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Java as a plug-in is quite w idespread and allows small applicatio ns kno w n as applets to run in the web browser. Java was revo lutio nary in that w ay w hen it was released, but it suffers fro m a lo t of issues: • Java is no to rio usly slow. It's slow to install on a new computer, and especially slow to start. • Java applets have a bad reputatio n w hen it co mes to security. This claim might no t be as true in new er versions as it used to be, but Java's ado ptio n in the corporate w orld has suffered a lot fro m this co ncern. • Java is cumberso me for .NET developers. The to o ls and the language are unusual and require additio nal training. Silverlight addresses these co ncerns and offers a co nvincing alternative to Java applets. Perhaps the mo st co mpelling argument is thatzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight is .NET. If your developers already kno w .NET-based client applicatio n techno lo gies (WPF, Windo w s Forms, ASP.NET, and so on), they w ill feel at ho me very fast w ith Silverlight, and have a solid fo und atio n to build on. M icrosof t Act ive X

Similarly to Java applets, A ctiveX co ntro ls were o nce very popular to enrich a web page, but are rendered pretty much o bso lete now adays by the many impro vements made to new techno lo gies, and especially Silverlight. If yo u are a developer or maintainer of A ctiveX co ntro ls, it is pro bably time to consider mo ving to the new er, richer, and safer platfo rm that Micro so ft is developing. A ctiveX co ntro ls suffer from the same pro blems as Java applets regarding security and restrictio ns in the enterprise w orld; in addition, they run o nly on Window s-based operating systems, w hich prevents a large user base from using them. Silverlight differs significantly fro m A ctiveX, and co nverting existing applicatio ns to this new techno lo gy is no t the easiest task a developer can dream of. W ith this step, how ever, yo u w ill offer a newer, richer, and much friendlier interface to your users, and make a big step tow ard the future of softw are develo pment.

A Short Hist ory of Silve rlight The d evelo pment of Silverlight has been co nsistently incremental. Silverlight 4 is a superset of Silverlight 3, w hich is a superset of Silverlight 2. So me of the code might no t be co mpletely co mpatible betw een versions, mo stly because w hen some things were missing developers had to use w orkarounds. After a feature has been added in a later version, how ever, the w orkarounds might no t w ork properly anymo re, and it is time to upgrade the code to the proper imp lementatio n. In some rare cases, the interface to some functio nality might have changed because the team came up w ith a better imp lementatio n. These o ccurrences are rare, how ever, and upgrading an applicatio n to a new er version of Silverlight sho uld be easy eno ugh.

16

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

Silve rlight 1 .0 zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA This early release of Silverlight (May 2007) was far fro m co mplete, and in fact did no t support any .NET code; it had to be pro grammed in JavaScript. It did, how ever, support a small subset of XAML (extensible A pplication Markup Language), the language used to define the user interface of Silverlight applicatio ns.

TI P Vi d e o a s a n I n ce n t i ve

St udies have shown that a user is m ost likely going to accept installing a new plug-in on his com puter to watch videos. This is why the m ain focus has been put on video in Silverlight 1 .0 .

v

/

The main purpose of Silverlight 1.0 was to rapidly create a base of installatio n for the Silverlight plug-in. Other features were, how ever, supported in Silverlight 1.0. For example, yo u could already create some animatio ns. There were no built-in co ntro ls (apart from the TextBlock), but using shapes, yo u could create butto ns and o ther basic building blo cks for your Co d e N a m e W P F / E applicatio n that w ould trigger You m ight have heard the nam e Windows JavaScript-based code. For instance, Presentation Foundation Everywhere, or some video players still available to day WPF/ E. This was the code nam e under which o n the Web are entirely w ritten in Microsoft developed Silverlight, in reference Silverlight 1.0, w itho ut any .NET code. Now adays it is clear that Silverlight 1.0 was just a step o n the road to rich interactive applications, and very so o n the fo cus shifted to Silverlight 2, the first .NET-based version.

to Windows Presentation Foundation, the rich desk top program m ing fram ework included in .NET 3 .0 and later. Very soon, however, this nam e was abandoned in favor of the catchier Silverlight. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH s,

Silve rlight 2 For a very short time, this version was named Silverlight 1.1, but considering the majo r changes implemented (and also to simplify the versio ning process), it made sense to change the version number to a full digit instead. Silverlight 2 (released sho rtly before the Professional Developer Co nference in Octo ber 2008) was revo lutio nary because it bro ught for the very first time the .NET framew ork (as a subset) to o ther platforms than Window s. It also included a rich set of controls, enhanced video, new to o l support, and many o ther exciting features. W hen yo u study Silverlight 4, yo u w ill use a lo t of features that were already available in Silverlight 2.

Silve rlight 3 This version (again a full-digit increment) was released in July 2009, a mere nine mo nths after Silverlight 2. In this short time, the team managed to bring Silverlight to a mo re mature version.

>

P r e v i e w i n g t h e Fu t u r e o f Si l v e r l i g h t

17

zyxwvutsrqponml

Controls and features were added, and the data layer extended to provide a stable foundation for more business-oriented scenarios. At the same time, the existing media layer was extended w ith new formats being supported, and new powerful effects (known as pixel shaders) being introduced. On the user experience level, it was now possible to transform 2D elements into the 3D space (what was sometimes called "pseudo 3D" or "2.5D"). A nimations were pushed further, w ith smoother and more lifelike mo vement. Some steps were also taken to enable hardware acceleration (which is a real challenge on mixed platforms such as the ones supported by Silverlight). It's also in Silverlight 3 that we saw the out-of-the-brow ser (OOB) feature for the first time. It was still rather incomplete: For example, the OOB application still couldn't get any additional permission, so it was pretty limited in its actions. It was also no t possible to give a custom look and feel to the OOB window. Still, it was an intriguing first step, and the community's response was very encouraging. In short, we w anted mo re... zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

And Silve rlight 4 ... And here we are! Silverlight 4 will no t be the final version of this technology, but one thing is sure: If you were still hesitating to invest in Silverlight, now is a great time to start. We know a lot about w hat Silverlight is, w hat it can do and canno t do, and we have a quite clear vision of w hat will happen in the near future. We also have Silverlight experts w ith (in some cases) two or three years of experience w ith this technology. Silverlight 4 is a very stable release. What we predicted w hen Silverlight 2 was published is proven true today: Silverlight is here to stay, and Microsoft is betting a lot on this technology. In these three years, it w ent from "Flash contender" to major user interface technology. According to recent numbers, the Silverlight installation basis grew very fast since Silverlight 2 was released, and you can count on approximately 60% of all the connected computers having Silverlight 3 or Silverlight 4 already installed.2

Pre vie wing the Future of Silve rlight The next burning question, of course, is where Silverlight is going. As usual, predicting the future of any techno lo gy is a difficult exercise, as the past few years have proven. The situation on the .NET front is a bit clearer now than it was two years ago, though; so w hat did we learn? • Silverlight has strong support at Microsoft. They are pushing it very hard; they release new features at a fast pace, and managed in just a few years to create a very rich framework. This is no t going to stop w ith Silverlight 4; more is coming.

• A convergence is occurring betw een Silverlight and WPF. More and more features are shared. The mo vement is toward compatibility, w ith Silverlight becoming a complete subset of WPF. Not just compatibility of interfaces, but also binary compatibility. We will probably see this happening in the next few years. yxwvutsrqponmlkjihgfedcbaWUSRP 2

Source:

http:/ / riastats.com

18

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

TI P N ot Co m p l e t e l y Co m p a t i b l e Ye t

Today, Silverlight is already in great part a subset of WPF in term s of interfaces. Many classes that are in Silverlight also exist in WPF. However, som e new classes have been added to Silverlight 3 and 4 ; som e of them have m ade it into WPF 4 , som e of them are still m issing. The situation is not as clean as one would want. Also, even though we see first st eps in that direction, the binary com patibility is still lim ited,

v

zyxwvutsrqponmlkjihgfed /

• There is already a large ado ptio n of Silverlight by developers and firms w orldw ide. We saw lots of interesting pro jects in the past few years, and mo re are co ming. We also see a lot of firms that were reluctant to mo ve to WPF embracing Silverlight for their rich applicatio n d evelo pment because it is easier to learn. • Finally, the installatio n base has literally exploded, going fro m appro ximately 25% for Silverlight 2 to 60% for Silverlight 3 and 4. The smo o th update mechanism makes it painless to upgrade Silverlight if needed; and as new applicatio ns are being published o n the Web, mo re users are installing Silverlight to access them. Here's a quo te from Pete Brow n, w ho w orks for Micro so ft as client applicatio n evangelist (http:/ / w w w .galasoft.ch/ sl4-convergence): In the future, it is very likely that both Silverlight and WPF will be a single technology with a single codebase.

So here it is, the probable future of Silverlight and WPF: A co ntinuum framew ork that can be used on the desktop (very rich clients w ith full features / rich clients w ith fewer features and permissions) and in the web brow ser (very similar to w hat we have now, but w ith added functio nality).

Insta lling Silve rlight 4 as a Use r Installing Silverlight 4 is very easy. For many users, a version of Silverlight might in fact be already installed on their computer. For instance, if yo u install o ne of the applicatio ns distributed under the label Window s Live (such as Live Messenger, Live Writer, and so o n) and keep the default options, Silverlight w ill be installed o n the target PC. Similarly, Silverlight can be installed by the Window s Update program. This enables administrato rs to make sure that the latest versions of Micro so ft applicatio ns are consistently installed in a corporate netw o rk. For ho me users, Window s Update is a great w ay to make sure that yo u get no tified w hen a new version of a driver, an application, or a framew ork (such as Silverlight) is available. That said, because it is so new, yo u might no t have the latest version of Silverlight and w ill need to upgrade w hen yo u navigate to a Silverlight 4 applicatio n in your w eb browser. Or, yo u might no t have Silverlight installed at all, and here to o yo u w ill be no tified w hen yo u reach the page yo u w ant to see.

Ex p l o r i n g Si l v e r l i g h t 4 D e m o s

19

zyxwvutsrqponm

Opening a Silve rlight 4 Applica t ion zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE Silverlight applicatio ns are always embedded in an HTML page. Opening a Silverlight applicatio n for the first time is always a matter of navigating to a w eb page in a supported web browser. W ith the possibility of saving Silverlight applicatio ns lo cally and to run them o ut-o f-thebrowser, the startup p o int might no t be a web page anymo re, but mo re classically a shortcut in the Start menu or on the desktop. However, an applicatio n may o nly be installed lo cally follow ing a user actio n (for example, a click on a butto n or a right-click on the applicatio n and selecting Install fro m the Silverlight co ntext menu). It always starts on the web page!

W ha t to Do If Silve rlight Is Not Insta lle d? If Silverlight is no t installed at all on the co mputer yo u are using (no t even an earlier version), yo u w ill see an image asking yo u to install Silverlight, as show n in Figure 1.2. Note, how ever, that this experience can be customized, and yo u might see different pages w ith elaborate designs.

I nstall

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO

M icrosoft " Silverlight

t o experience this site

4 MB download yxwvutsrponmlkjihgfedcbaYXWVUTSRQPOM Click t o I nst all 10 s e c o n d in s t a ll

FIGURE 1 .2 Silverlight.

Install Microsoft

Exploring Silve rlight 4 Dem os Now that Silverlight 4 is a little older, it is possible to see some nice samples o n the w eb. To see these demos, yo u just need to install Silverlight 4 and to navigate to a URL.

Deep Zoom ing the M a t t e rhorn The Matterho rn Deep Z oom applicatio n was developed by Micro so ft Sw itzerland to celebrate their 20th anniversary in Sw itzerland. It features multiple gigapixel pictures stitched to gether and processed in order to be rendered by the DeepZ oom techno lo gy. We already talked about DeepZ oom in Silverlight 2 Unleashed: A co mpo ser applicatio n prepares a large image by splitting it into a co llectio n of tiles. Multiple reso lutio ns of each tiles are prepared. W hen the image is loaded in the DeepZ oom viewer (pow ered by Silverlight), the user can zo o m in or out (for example using the mo use w heel or, if he has a supported multito uch screen, w ith a "p inch" gesture). W hen the image is zoomed, the DeepZ oom view er dynamically loads the corresponding tiles from the server. To render the experience mo re d ynamic for the user, the tiles are loaded at low reso lutio n first, and then gradually the image is rendered w ith a finer grain until the maximum reso lutio n is reached.

To start the Matterho rn DeepZ oom applicatio n (show n in Figure 1.3), navigate to http:/ / w w w .galasoft.ch/ sl4-matterhorn. Clicking on the demo sets the applicatio n in full screen. Select o ne of the pictures and use the mouse's w heel to zo o m in. No tice ho w the zo o m actio n is smo o th, and ho w the tiles, blurry at first, beco me sharper as mo re zyxwvutsrqponmlkjihgfedcbaY

20

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

info rmatio n is loaded by the applicatio n. More info rmatio n about the pictures can be seen by clicking on the "info " butto n, w hich is a nice w ay to enrich a presentatio n.

FIGURE 1 .3

The Matterhorn DeepZoom application.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHG

Ge t t ing Involved Socia lly wit h Sobe e s In today's World Wide Web, social netw orks have gained in popularity to beco me an unavo idable part of the brow sing experience. Many people, how ever, do no t use the social w ebsites but prefer to use a rich aggregator instead. Sobees offer such applicatio ns for multiple platforms, including o ne built in Silverlight 4 and running either in the brow ser or installed out-of-the-brow ser. The Sobees applicatio n can be used to visualize entries fro m Twitter, Facebook, MySpace, and Linkedln w ithin o ne single w indow . It is also possible to perform multiple searches on Twitter. To run the Sobees Silverlight applicatio n (show n in Figure 1.4), navigate to http:/ / sobees.com/ web. Follow the instructio ns to co nnect to the services that yo u w ant to aggregate. In order to install the applicatio n and run it like a no rmal Windo w s (or Mac) application, right click anyw here on the applicatio n's surface and select Install Sobees web alpha o nto this computer. After co nfirming the o peratio n, this creates a shortcut in your Start menu and/ or o n your desktop that yo u can use to run the applicatio n w itho ut starting the web brow ser.

Ex p l o r i n g Si l v e r l i g h t 4 D e m o s

21

I

IyxwvutsrponmlkihgfedcbaYWVUTSRPONMLIHGFEDCBA s o b e s s iSI

SyxwvutsrponmlkjihgfedcbaYXWVUTSRQPOMLKJIHGEDCBA zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA D e r ik W h r t t a k e r

Jonan Ribeit RT ' Jj] ridyiromoz

;i]LUu qn : t,s]Vhurram

R1 in lh a e m u la t o r a n d t h e o n - s c r e e n k e yb o a r d fcs d is p la ye d , p r e s s P a u s e / Bi e a k lu a cliva t u P C k e yb o a r d

< 2 4 h o u r s o f u s in g t h e W P / i c a n s a y t h a t le a vin g m y iP h o o fi fo r a W P 7 wo u ld n ot b e a m a s s i ve i f n i » - th is is w/ out a n y a p p s t o o

wh en

#wp7dev tfwpfou 3 nvnuln agsoljchcj u J* about 9 hum ago R rpttj/uiionht yxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB Man J u s t go t b a c k fr om b r u n ch in Ba y R t d go . R e h mt Mem R r p l > 0 4 mmu M l ogc [ - _ Rrply Rrt-vi-i-t Mirjr lndyTromo7 RT Rngninn @khurram w h e n in Ih ft e m u la lo f 1 susandelaney a n d t h e o n s c r c o n k e yb o a r d is d is p la ye d , p r e s s • sweet freedom - epiraJing joy P a u s e / I 3 r e a k t o a ct iva t e P C k e yb o a r d tt •, p Tde #wp7an (f rluud R hours Ago biowdart Keofy Netrtcct More . W o w la m b h> e x p e n s i v e h e r e Slill, g a l s o m e n i ce c u t s s o In sh S t e w t o d a y, d e s p i t e t h e h e a t } zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA LBugnion 5 minut« ago '

Kepty KclwMt More

1

andlju

i 1

1

l^ nluu) 11 ham ngo

Kcpfy Hetwcc! More

In

Did yo u k n o w yo u c a n run a n d d e b u g W e b P a g e s ( c s h l m l ) fr om with in Vis u a l St u d i o 7 0 10 ? II ju s i

ww tailffwebmatrix Rriwri-tleiUm JRerpty iemydmi

Be r i H a ya t Lot m e k n o w, w h e n yo u n e e d fe e d b a c k lo r e lu m .

igLBugniofi

fa mmults Dflo -

I

t think t o d a y a n d n e xt w u e k ' s l e s s o n in p r o gr a m m in g

Hep l

Tbuj®

FIGURE 1 .4

. © fcn u iia m w h e n in t h e cm u la t o f a n d t h e o n - s cr e e r i k e yb o a r d is d is p la ye d , p r e s s P a u s e / H r e a k lo a ct iva t e P C k e yb o a r d

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB tt p7ttov

of use

Piwjcy puky

Pie»

tho

t? about 11 I n » ago Rifity Ri*t*ivr More

vtsrnmlkihgedcaVUSRNMKEA

Investors

Jut>t

Contact

Bfeg

Fufcw j el> uri; [j]

Sobees Silverlight application.

Na viga ting wit h Bing M a ps St re e t side and PhotoSynth Bing maps and the Streetside applicatio n are an interesting w ay to navigate geographical maps and to immerse yourself in a city either to discover it in advance or to remember w here your steps to o k you. Note that the "classic" Bing maps applicatio n uses standard web techno lo gies; to get the Silverlight version, follow the URL: http:/ / www.bing.com/ maps/ explore. After the applicatio n is loaded, use the mo use w heel to zo o m into the map. Note the smo o th loading of details, pow ered by Silverlight. As yo u zo o m in, the level of detail changes, and sw itches from map view to satellite view. This can be co ntro lled using the "+" and "- " butto ns on the bo tto m of the page (show n in Figure 1.5). Two additio nal features are available in selected areas: Streetside and Pho to Synth. Exploring the St re e t s w it h St re e t side

The idea behind Bing maps Streetside is no t new but Silverlight provides a very smo o th and inno vative experience. First, yo u need to lo cate a region w here Streetside is enabled. Click the seco nd butto n fro m the right in the co ntro ls at the bo tto m of the page, as show n in Figure 1.5. This adds a number of blue areas to the map. Use the zo o m co ntro ls to dive into o ne of these areas (for example the city of Seattle in the USA).

SaawwAnto

FIGURE 1 .5 cont rols.

~

Bing m aps

22

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

After entering the Streetside view, yo u can use the mo use to click aro und your lo catio n and navigate the available area. It is interesting to see ho w the pictures are deco nstructed and reco nstructed to provide an impression of speed as the view advances along the streets. It is also possible to press and ho ld the mo use to pan the picture around, and the mo use w heel to zo o m in and out. For example, the Seattle A quarium building is show n in Figure 1.6.

FIGURE 1 .6

Bing m aps Streetside in Seattle.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDC

D iscove ring a La ndsca pe w it h P hot oSynt h

The Pho to Synth techno lo gy uses Silverlight to co mbine multiple pictures taken aro und a same o bject (building, mo nument, landscape, and so fo rth). To dive into a Pho to Synth from the Bing Maps viewer, lo o k for a small ico n as show n in Figure 1.7. Once the Pho to Synth view er is started, use the mo use to click on the panes show n in Figure 1.8, in order to see a different view

FIGURE 1 .7

PhotoSynth icons.

Ex p l o r i n g Si l v e r l i g h t 4 D e m o s

23

zyxwvutsrqponml

of the same o bject. The view is co mpo sed of multiple pictures stitched to gether auto matically. Silverlight is used to smo o thly pass fro m o ne picture to ano ther, providing an impression of 3D as the viewer navigates around the o bject. For mo re info rmatio n about Pho to Synth, refer to http:/ / photosynth.net/ .

FIGURE 1 .8

PhotoSynth of the Statue of Liberty.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

Visua lizing Inform a tion wit h the Pivot Vie we r The Silverlight Pivot viewer is an inno vative w ay to display large quantities of info rmatio n and to sort it. So me examples start being published on the Web, for example the page at http:/ / www.galasoft.ch/ sl4-pivot w hich represents all the editio ns of MSDN magazine since 2000. Using links or a search bo x, yo u can refine the search as show n in Figure 1.9 and Figure 1.10.

24

CH A P TER 1

FIGURE 1 .9

Th r e e Ye a r s o f Si l v e r l i g h t

Pivot Viewer: All MSDN editions.

OpcnMParvdC* * :

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Reap the Benefits of Muftfttoteadng without All the Work

Asynchronous Pages in A SP N ET 2. 0

(£) • l ULI-* iMQWtld

i • Founda trans X • Data Points. W P f yxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB : u u • ADON . ÊT En« Usin togg T T* empi nplj««* to Cuftomi»S>mI C © HU I Ovrrwew Windows Prdentation WPF Control» zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Foundation

Cotumn Name Has Code

FIGURE 1 .1 0

Pivot Viewer: MSDN editions by popularity, zoom ed in.

Ho w Ca n Yo u Ge t I n v o l v e d ?

25

zyxwvutsrqponml

The Pivot Viewer is but o ne possibility to represent info rmatio n in a rich manner w ith Silverlight. In this bo o k, we w ill work w ith data o ften and create rich co nnected business applicatio ns w ith Silverlight. The power of co mputatio n that Silverlight has over classic web solutions, as w ell as inno vative representatio ns such as show n in Figures 1.9 and 1.10 allow creating co mpelling experiences. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Dra wing on the W eb wit h Fa nta sia

The Fantasia drawing applicatio n demo nstrates some advanced graphics features of Silverlight 4, such as using loading and mo difying pictures, adding effects to a scene, o pening pictures fro m Flickr directly, and saving the result as an image file lo cally on the computer. We w ill talk about many of these features, especially in Chapter 16, "Using Effects and Recording Med ia." The Fantasia drawing applicatio n show n in Figure 1.11 is a nice place to see all these in actio n, and to realize w hat advanced graphics features are included in this version of Silverlight. It is available at http:/ / nokola.com/ fantasia/ . zyxwvutsrqponmlkjihgfedcbaZY

A

Life- like C

FIGURE 1 .1 1

The Fantasia Drawing Application.

How Ca n You Ge t Involved? If yo u are (or w ant to beco me) an active Silverlight developer, there are ways to make yourself heard. You can co llabo rate w ith your local Micro so ft d evelo pment and platfo rm evangelists, or participate in the fo rums at http:/ / silverlight.net, the official ho me page of Silverlight, w here yo u w ill get all the info rmatio n needed to get started.

26

CH A P TER 1

Th r e e Ye a r s o f Si l v e r l i g h t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

The Silverlight.net w ebsite (show n in Figure 1.12) is also w here yo u w ill find even mo re info rmatio n about Silverlight, compatibility, d eplo yment tips, samples to help yo u get started, and so o n.

toing g) HzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA wtih Gel Stalled LealRI Shuv.u ' ase OufTiriumLy Fwurris Microsof t " Silverlight

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Silverhylil iu a pawerlul development platfpiiti for Creating engaging, interactive user experiences for Web, desktop, and mobile nppfienhnni *4ien onlinr or offlinr. >4jr Learn why iillvcrilght U rtght (or you f^ Get Started with Sllverlmht Q

SlIverlMlhl for Window« Phone . View rammnnltv Sunpln

Qa VJrlrn Tutnrlnk I '< silverlight Ronta*

FIGURE 1 .1 2

The Silverlight.net landing page.

A no ther great w ay to get invo lved in the Silverlight co mmunity is to participate in o ne of the many Silverlight user groups that have been created around the w orld. You can find mo re info rmatio n about the Silverlight co mmunity at http:/ / silverlight.net/ community. Finally, many Silverlight experts and members of the Micro so ft Silverlight team are on Twitter. You w ill find their usernames at http:/ / w w w .galasoft.ch/ sl4-tw ittermvp and http:/ / w w w .galasoft.ch/ sl4-tw ittermsft.

Sum m a ry This chapter explained w hat Silverlight has to offer for client applicatio n developers in terms of skills reuse (for .NET programmers) and cross-browser, cross-platform co mpatibility. We talked about a few alternative techno lo gies, bo th in the w eb brow ser and outside. Then we saw ho w Silverlight evolved in the past few years to beco me Silverlight 4, and talked about the future. Finally, we installed Silverlight 4 (if it was no t there already) and visited a few demos show ing off some nice features available in the framew ork. In the next chapter, we install the to o ls that we need to develop Silverlight applications, and take a tour of their features. This w ill be very impo rtant because we w ill spend many ho urs in tho se tools, bo th in this bo o k and, sho uld yo u like Silverlight, after yo u have finished reading.

CH A P TER

2

Setting Up and Discovering Your Enviro nment Be f o r e we start programming, we need to install and configure some tools. We w ill also take a short tour of the applicatio ns in w hich yo u are going to spend quite a lo t of time w hile yo u read this bo o k, and ho pefully after yo u are done reading, to o !

Insta lling Visua l Studio Nowadays, the line betw een design to o l and d evelo pment to o l is a little mo re blurry than it used to be, w ith the additio n of visual designers in Visual Studio and of code editors in Expression Blend. Still, some people tend to prefer o ne or the o ther for a given activity. The best is to try all the to o ls for yourself and to decide w hat yo u prefer depending on w hich activity yo u perform.

Visua l St udio 2 0 1 0 This is the (almost) unavo idable step for any .NET developer, and Silverlight is no exceptio n. Installing Visual Studio w ill give yo u access to the full range of .NET techno lo gies, server side and client side. If yo u are an experienced developer in .NET, yo u pro bably already have Visual Studio installed o n your PC. Unfortunately, it is no t sure that yo u have the right version: You need Visual Studio 2010 to develop Silverlight 4. Visual Studio can be dow nloaded from http:/ / www. galaso ft.ch/ sl4-vsl0.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML I N TH I S CH A P TER , W E W I LL: » Install Visua l Studio 2 0 1 0 and the Silverlight tools for this Integra ted Developm ent Environm ent (ID E). •

Crea te a first Silverlight 4 a pplica tion and inspect its files.



Use the Visua l Studio designer and understand the relationship between XAM L and design.



Install Expression Blend and use it to add an effect and an anim ation to the Silverlight a pplica tion. zyxwvutsrqponmlkjihgfedcbaZYXWVUT

28

CH A P TER 2

Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

If yo u have an MSDN subscription, Visual Studio is available to yo u as part of the subscription. Depending on your subscription, yo u might have a more- or less-elaborate version of Visual Studio, w ith mo re or fewer additio nal tools, but yo u d o n't need tho se to build Silverlight applicatio ns.

W A R N I N G zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Vi su a l St u d i o 2 0 1 0 On l y

Silverlight 4 can be developed only in Visual Studio 2 0 1 0 , not in earlier versions. Note, however, that Visual Studio 2 0 1 0 can be installed side by side with earlier versions without issues. Also, Visual Studio 2 0 1 0 can be used to create and m aintain applications in Silverlight 3 and in Silverlight 4 .

v

/

Visua l W e b De ve lope r Expre ss As w ith earlier versions of Silverlight, it is also possible to develop Silverlight 4 applicatio ns using the free edition of Visual Studio for the Web: Visual Web Developer Express. Of course, the free editio n is mo re limited than the co mmercial one, but it provides a great place to start at no cost. Visual Web Developer Express can be dow nloaded fro m this address: http:/ / w w w .galasoft.ch/ sl4-w ebexpress. In this bo o k, we use Visual Studio 2010 for the samples, but yo u sho uld be able to easily adapt the steps to Visual Web Developer Express.

TI P Ch o o si n g a P rogra m m in g La n gu a ge

Silverlight can be program m ed in Visual C# or in VB.NET. Depending on your past experiences, you may choose one or the other indistinctly. Other .NET languages are support ed, too (for exam ple, the dynam ic languages IronPython and IronRuby). \

/

Inst a lling t he Silve rlight Tools for Visua l St udio Once Visual Studio (or the Express editio n) is installed, yo u need additio nal to o ls for Silverlight 4 develo pment, to be dow nloaded at http:/ / www.galasoft.ch/ sl4-tools (Silverlight 4 Tools for Visual Studio 2010).

These co ntain the follow ing elements: zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA • The Silverlight developer runtime: This is a special version of the Silverlight plug-

in that Visual Studio can attach a debugger to, to help yo u understand w here issues co me from, and to solve them. • N ew templates for V isual Studio: These are used to create new pro jects and new

items (pages, controls, classes, and so o n) in your Silverlight applicatio n.

I n s t a l l i n g Vi s u a l St u d i o

29

zyxwvutsrqponm

• The Software D evelopment Kit (SDK) for Silverlight:zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM This kit co ntains all the

libraries yo u w ill need to create and deploy Silverlight applications, to o ls to create and package Silverlight applicatio n (for example, o n a build server), and po inters to additional resources o nline such as the official Silverlight d o cumentatio n. After yo u have installed the Silverlight to o ls for Visual Studio, yo u are ready to create your first Silverlight applicatio n. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

Verifying the Insta lla tion The best way to verify the installatio n is to create a new Silverlight applicatio n. We w ill also use this o ppo rtunity to discover basic Silverlight-related functio nality in the enviro nment. Follow these steps: 1. Start Visual Studio 2010. 2. Select File, New, Pro ject. 3. In the New Project dialog bo x, select the Silverlight category on the left, and create a new Silverlight A pplication named HelloSilverlight, as show n in Figure 2.1.

FIGURE 2 .1

New Project dialog box.

4. In the next dialog bo x, show n in Figure 2.2, cho o se w hether yo u w ant to create a

new Web A pplication Project, a new ASP.NET Website, or a new ASP.NET MVC applicatio n to ho st the Silverlight applicatio n.

30

CH A P TER 2

Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQP

Cl i ck t h e ch e ck b o x below l : i h o st t h i s Silver ligh t applicat ior t est p age w ill be gen er at ed d u r i n g b u i l d

| 7] Ho st t h e Silver! i gh l applicat ior

New W e b pr oject nam e; Helf oSihier light .W eb New W e b pr oject t y p e A5 P.N ET W e b Ap p l i cat i o n Pr o j ect

Op t i o n s Silver! igh t Ver sion: 5 i i vei i r gh t t g

Enable .NET FUA Ser vices

OK

FIGURE 2 .2

| |

Can cel

New Silverlight Application dialog box.

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHG

Cho o sing betw een web applicatio n pro ject, w ebsite, or MVC applicatio n depends on w hat yo u w ant to achieve, personal preferences, w hat existing w ebsite yo u w ant to integrate your Silverlight applicatio n into , and so fo rth. The Silverlight applicatio n w ill be strictly the same, o nly the ho sting web applicatio n w ill differ. The experience show s that web applicatio n pro jects are mo re flexible than ASP.NET w ebsites, so this is w hat we w ill use in this bo o k. ASP.NET MVC applicatio ns are also very interesting and offer a nice alternative to ASP.NET w eb applications. For mo re info rmatio n abo ut ASP.NET, check out the w ebsite at http:/ / www.asp.net. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

TI P Cr e a t i n g a W e b P r o j e ct or N ot

It is not com pulsory to create a web project to host the Silverlight application. You can either create one later or attach your Silverlight application to an existing ASPNET web project. You can also create the Silverlight application without any host, and run it from a sim ple HTML page. If you do not create a web project, Visual Studio and Blend will generate a t est HTML page for you and open it in the web browser when you run the application. s

To understand better w hat is happening, let's create a new web applicatio n pro ject for this new applicatio n:

1. In the New Silverlight A pplication dialog bo x show n in Figure 2.2, check the first check bo x and make sure that ASP.NET Web A pplication Project is selected in the co mbo bo x. You can also enter a name for your web applicatio n and then click OK. zyxwvutsrqponmlkjih 2. Make sure that Silverlight 4 is selected in the Silverlight Version co mbo bo x. Visual

Studio 2010 allow s creating Silverlight 3 applicatio ns w itho ut installing additional tools, and Silverlight 4 applicatio ns after yo u install the Silverlight to o ls for Visual Studio like we did earlier in this chapter.

I n s t a l l i n g Vi s u a l St u d i o

31

zyxwvutsrqponml

3. Do no t check the Enable .NET RIA Services check bo x for now . We cover this o ptio n in Chapter 13, "Creating Line-of-Business A pplicatio ns." zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPO 4. Click OK.

5. To make sure that we have all the files ready, build the application by selecting Build, Build So lutio n fro m the menu. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB

Inspe ct ing the Applica t ion Based on the ind icatio ns we gave, Visual Studio created tw o projects, as show n in Figure 2.3. It is indeed possible to mix Silverlight applicatio n and "full .NET" applicatio ns in a single so lutio n. Let's review the pro jects and the files: • HelloSilverlight is the Silverlight applicatio n itself. It co ntains four impo rtant files: A pp.xaml and the attached A pp.xaml.cs co ntain the global application o bject, global event handlers, global resources, and so on. This is also the main entry po int for the applicatio n.

-

S o l u t i o n E xp lo r e r

S o l u t i o n ' H e l l o S i l ve r l i g h t ' ( 2 p r o j e c t s )

X

zyxwvutsrqponmlkjihgfedcbaXWVUTS

H e l l o Si l v e rl i g h t

A

>

P r op er t ies

&

R e fe r e n ce s

A

[ *] Ap p j c a m l ^

A

J8

Ap p j c a m l . c s

Ma ïn Pa gejt a m l ^

A

Y

Ma r n P a gejt a m l.es

H e l lo Silve r lig h t . W e b

>

P r op er t ies

>

R e fe r e n ce s

A

CI Ten t Bin H e llo Si lve r li gh t J ca p

M H e l[ o Sit ve r ligh t Te s t P a ge .a s p * MainPage.xaml and the attached 0 H e l l o S r t ve r l T g h t T e s t P a g e . h t m l MainPage.xaml.es are like the name Sit ve r figh t . js & W e b .co n fr g indicates the main page for the applicatio n. You can have multiple pages in FIGURE 2 .3 The created projects in the the applicatio n; the main page is the Solution Explorer. o ne that is created w hen the applicatio n starts. yxwvutsrponmlkjihgfedcbaYXWVUTSRQPOMLKJIHGEDCBA

• HelloSilverlight.Web is the w eb application, running on ASP.NET. It co ntains the files that w ill be dow nloaded to the web browser. • ClientBin\Hello Silverlight.xap is a zip file w ith all the binary files needed to run the applicatio n in the plug-in (in our case, this is just HelloSilverlight.dll), and a file named A ppManifest.xaml, called the applicatio n manifest. It co ntains info rmatio n that the plug-in needs to start the applicatio n, as w ell as o ptio nal ind icatio n about the possibility to run the applicatio n out of the browser, and so fo rth.

• HelloSilverlightTestPage.aspx and HelloSilverlightTestPage.html are tw o generated test pages ho sting the Silverlight applicatio n. If yo u open either file, yo u w ill see generated HTML and JavaScript code, including thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHG obj ect tag w ithin w hich the Silverlight plug-in w ill run. • Silverlight. js is a utility file w ith JavaScript functio ns that can be interesting to use w ithin the HTML page. For example, there is a functio n helping yo u to check w hich version is installed on the client PC, and to react acco rdingly by alerting the user.

32

CH A P TER 2

Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

Unpa ck ing an XAP File zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA If yo u w ant to lo o k by yourself at the co ntent of a XAP file, follow these steps:

1. Right-click the ClientBin folder in the So lutio n Explorer, and select Open folder in Windo w s Explorer fro m the co ntext menu. zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHG 2. Make a co py of HelloSilverlight.xap and rename it to HelloSilverlight.zip.

3. If the operating system supports it (for example, in Windo w s 7), yo u can open the zip file just like any o ther folder and see the co ntent. 4. On operating systems that do no t support this functio n, yo u can use a zip to o l to

unpack the XAP file. Note that if yo u w ant, yo u can recompress the XAP file w ith a higher level of compression and get smaller files to send to the w eb browser. The file w ill be transmitted faster, but it w ill take mo re time to unpack it to start the applicatio n.

Using the Visua l Studio De signe r

Open the file MainPage.xaml. If yo u didn't change the Visual Studio settings, yo u should no w see some XAML code. XAML is an XML-based language used in Silverlight and Windo w s Presentatio n Fo undatio n (WPF) to describe the user interface. There are o ther possible usages for XAML, and in fact it is really just a serialization language for .NET. If yo u w ant mo re info rmatio n about XAML, yo u can refer to zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJI Silverlight 2 Unleashed, Chapters 2 and 3.

TI P Op e n i n g in t h e D e si gn e r or in t h e S o u r ce Ed it or

By default, XAML files open in the Visual Studio designer. However, the designer tak es som e tim e to st art . Many developers prefer to change the default by following t hese st eps: 1. Right-click any XAML file.

2. Select Open With from the context m enu. 3. In the Open With dialog box, choose Source Code (Text) Editor. If you want, you can set t his as the default using the corresponding button. 4. Click OK. Opening XAML files will be faster now, but you lose the designer functionality. To open a XAML file in the designer anyway, follow t hese st eps: 1. Right-click the XAML file.

2. Select View Designer from the context m enu. \

W ith MainPage.xaml o pen in the designer, yo u should see tabs at the bo tto m, as show n in Figure 2.4.

/

Im plem ent ing Hello Silverlight

On the o ther side of the bar, yo u w ill see three small butto ns and a grip, as show n in Figure 2.5. The butto ns and the grip in Figure 2.5 and the tabs in Figure 2.4 are used to sw itch betw een XAML view and design view, or to split the editor w indow and have the XAML and the design on the same screen:

"I

33

zyxwvutsrqponml

zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE a UserControl

HXAML I

Design

FIGURE 2 .4

H

U s p r f. r . n t m l

V

Bottom of the XAML editor.

tDHIB FIGURE 2 .5

Grip and split but t ons.

• Use the XAML tab to see the XAML code, and the Design tab to see the scene in the designer. • Use the grip in Figure 2.5 to slide the separator up, and visualize the XAML code on top, and the design surface on the bo tto m. • Using the butto ns in Figure 2.5, yo u can split the editor vertically or ho rizo ntally and see the XAML and the design surface. The last butto n (w ith a double arrow) collapses or expands the design surface. If yo u d o n't like to have the XAML on top, yo u can sw itch the XAML and the design surface by pressing the small butto n w ith tw o arrows lo cated betw een the XAML tab and the Design tab, as show n in Figure 2.6. Note that this butto n is visible o nly w hen the w indow is split.

|zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED hxa m l ti q.DesigT~l A no ther impo rtant element of the visual designer is the property editor. W hen o ne element is selected in the designer, FIGURE 2 .6 Switching XAML and Design the property editor show s all the view, element's properties that yo u can modify. You w ill learn ho w to use the property editor in the next sectio n.

Im plem enting Hello Silve rlight To get to know Visual Studio a bit better, let's imp lement a simple applicatio n w ith the follow ing steps: 1. Set azyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Li near Gr adi ent Br us h in the main Gr i d by adding the XAML code fro m Listing 2.1 w ithin the Gr i d tag. You must co py these lines betw een the o pening tag and the closing tag . You must also remove the Backgr ound property that was set in the Gr i d tag initially. LISTING 2 .1

Setting a zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCBA Li ne ar Gr adi e nt Br us h







  • zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Che ck ing the Prope rt ie s Editor zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB If yo u are no t quite sure w hat yo u are lo o king at and w hat a brush is in Silverlight, yo u can refer to zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed, Chapter 4. W ith the visual designer open (in full-w indow or in split mode), yo u sho uld no w see the scene show n in Figure 2.7. In this figure, no tice the bread crumb bar in the bo tto m, w ith the full path leading to the element that is selected in the XAML editor (in this case, the Li near Gr adi ent Br us h) . Passing your mo use o n o ne of the elements in the path w ill display a small thumbnail of the element in question, w hich is very useful w hen yo u try to isolate a given element in a co mplex user interface.

    FIGURE 2 .7

    Grid background in the visual designer.

    2. W ith the Li near Backgr oundBr us h selected in the XAML editor, press F4 (or select View, Properties Windo w fro m the Visual Studio menu). 3. You sho uld no w see all the properties of the brush in the Properties w indow , as in Figure 2.8; for example, no tice the GradientStops co llectio n, w hich define each "sto p " w here a color is applied. Silverlight then calculates the gradient betw een the different stops.

    I m p l e m e n t i n g He l l o Si l v e r l i g h t

    35

    P r n p « t i ( K zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDC Click the small butto n show n in 4.zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Figure 2.8 to open the GradientStops Co llectio n Editor. 5. On the left of the Co llectio n

    Editor, show n in Figure 2.9, select the GradientStop in the middle.

    no n am e*

    Li n c a r Gr a d i c n t B. . .

    P r o p e r t ie s 111 i i

    /

    I

    yxwvutsrponmlkihgfedcbaYWVUTSRPONMLIHGF

    E ve n t s

    p |

    I Se a r c h

    SRg b Li n ea i n t e r p o l a t i o n zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIF

    ffifflfffffl fl I f f t U . f f

    ^M

    7s

    H id P o in t



    Gr a d ie n t St o p s

    4

    Ma p p in gMn d p Op a cit y

    u ( Co lle ct io n ) H d a t r

    [

    j Edit i t e m s in t h is co lle ct i o n

    *=

    = 6. On the right, w ith the medium Sp ie d r fM e U iu d & Pod GradientSto p selected, expand St n r t P n in t QUO S ys t e m . W i n d o w s . M ed ia , Matr ixTr Tr a n s fo r m the Color property editor. yxwvutsrponmlkjihgfedcbaYXWVUTSRQPOMLKJIHGEDCBA *

    Kr ia t ivp f rantf n r m

    Sys t e m . W in d o w s . M ed ia . Matr ixTr

    FIGURE 2 .8 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCBA Li ne ar Gr adi e nt Br us h properties.

    P r n p wt i« :

    firarlipnrltnp Gm d icr ilSlu p Gr ad ien t St op

    FIGURE 2 .9

    Collection Editor for the GradientStops collection.

    7. Pick a new color for this gradient. 8. Using the Offset property, yo u can also mo ve the gradient from the middle (it is

    no w set at 0.5) to a different po sitio n. 9. Finally, using the Add butto n, yo u can set additio nal gradient stops w ith different colors, to create the brush that yo u desire. There are many different ways to mo d ify a property using the Properties editor, depending on the property's type. Everything yo u do in this editor is directly reflected in the XAML code. There is nothing hidden. So me developers prefer to edit the XAML markup, w hereas o thers are mo re visual and prefer the property editor, or even Expression Blend that we w ill use later in this chapter. Mo st pro bably yo u w ill find yourself somew here in the middle, and use bo th the XAML editor and the visual designer.

    36

    CH A P TER 2

    Finding a Prope rt y

    Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    W hen yo u have many properties in an element, it can be to ugh finding the correct o ne. Thankfully, the property editor helps yo u w ith the follow ing functio ns: • To sort the properties alphabetically and group them by category or by property source, use the small butto ns on the left of the Search bo x in Figure 2.8. • To lo o k a property up, use the Search functio n. It is very useful because the search fragment may appear w ithin the property name. For example, searching for the w ord zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA align w ill show bo th the Ho rizo ntalA lignment and VerticalA lignment properties.

    Cre a t ing Eve nt Ha ndle rs

    The Properties editor can also be used to create event handlers. To display all the events for a selected element, click the Events tab show n in Figure 2.8. In this case, we see all the events for the grid panel. Double-clicking in the field next to the event's name w ill add the event handler to the XAML code and implement the empty event handler in the code behind . A lternatively, it is also possible to type the event name in XAML and use IntelliSense to create the event hand ler in the code behind auto matically.

    Adding Som e Te xt We w ill no w add a text blo ck to our scene by follow ing the steps:

    1. Make sure that the To o lbo x is visible in Visual Studio. It sho uld be visible o n the far left of the Visual Studio w indow , just belo w the toolbars. If yo u do no t see the To o lbo x, select View, To o lbo x from the menu. zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIH 2. If the To o lbo x is collapsed, expand it by passing the mo use on the vertical To o lbo x

    butto n, as show n o n Figure 2.10.

    WARNING P op u la t in g t h e To o l b o x

    It can take som e tim e for the Toolbox to be populated with controls the first tim e that you expand it. If your Toolbox is em pty when you expand it, give a little tim e to Visual Studio to scan the assem blies and add all the controls to it.

    v

    /

    I m p l e m e n t i n g He l l o Si l v e r l i g h t

    37

    zyxwvutsrqponml

    E d it Vi e w Pr oject Bu i l d Debug Team DatJ I RE 3. From the Co mmo n Silverlight 5 B M * ¡ 3 vtsrnmlkihgedcaVUSRNMKEA A S -A &| 1 - V P Co ntro ls sectio n in the To o lbo x, I zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA Pu b l i s h tf M drag azyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Te xt Bl oc k and drop it on Toolbox the grid in the visual designer. — *

    C o m im o n S i t v e r l i g h t C o n t r o l s

    * Poin t er 4. W ith the new Te xt Bl oc k selected, n Bo r d e r in the property editor, click the Bu t t on name textBlo ckl just above the Ch e c k B o x S Properties and Events tabs. This m Co m b o B o x m D a t a Gr i d allows yo u to edit the name. For now, we d o n't need a name for FIGURE 2 .1 0 Toolbox. zyxwvutsrqponmlkjihgfedcbaZYXWVUTS this text blo ck, so yo u can just delete it. yxwvutsrponmlkjihgfedcbaYXWVUTSRQPOMLKJIHGEDCBA

    TI P N a m e , x:N a m e , or No N a m e

    The Name property is available only on certain XAML elem ents. On the other hand, you can add x:Name to any elem ent. (This is part of the ext ensibilit y in XAML.) Where available, the Name property is equivalent to the x:Name property. Nam es are often not needed, except if the elem ent is used in the code behind (for exam ple, to set som e properties program m atically). You also need a nam e if the elem ent is the source of a binding, the target of an anim ation, and so forth. Nam es can be useful when you t ry to structure a very com plex user interface with m any nested elem ents. Adding a nam e will, however, have a sm all im pact on perform ance, so it is recom m ended to avoid nam ing elem ents if possible. If you do nam e an elem ent, it is recom m ended to choose x: Name rather than just Name. Because x:Name is available everywhere, it brings m ore consist ency to your XAML code. \

    /

    5. Using the Properties editor or directly in XAML, find the Text property and set it to Hello Silverlight. Then change the follow ing properties: • Set the Hori zon t a l Al i gn m en t and Ver t i ca l Al i gn m en t properties to Center. • Set the Margin property to 0. • Set the Width and Height properties to Auto. • Set the Font Fam ily property to Verdana. • Set the Font Si ze to 72 and the FontWeight to Bold. • Finally, typezyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA W hite in the Foreground property. After yo u co mplete these steps, yo u sho uld see the image show n in Figure 2.11 in the visual designer.

    38

    CH A P TER 2

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

    TI P S t yl e s or D i re ct Va lu e s

    In a real-world application, such form atting will be applied to an elem ent using st yles. You'll learn m ore about st yles in Chapter 10, "Creating Resources, Styles, and Tem plates." zyxwvutsrqponmlkjihgfedcbaZY

    v

    /

    e llo Silve r ligl FIGURE 2 .1 1

    Text block with form atting.

    Short Re m inde r About Colors in Silve rlight

    We talked a lo t abo ut colors inzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed (Chapter 5, "Using Med ia"). If yo u need to refresh your memo ry yo u can check that chapter. Here is a quick reminder, tho ugh: • Colors are coded in XAML using three or four hexad ecimal numbers, each fro m 0 (# 00) to 255 (#FF). • The first tw o hexad ecimal digits define the A lpha transparency of the color. # 00 means that the color is co mpletely transparent, and #FF co mpletely opaque. These digits are o ptio nal. If they are o mitted, the co lo r is opaque. • The second, third, and fo urth positio ns define the Red, Green, and Blue channels. So, for example, the co lo r blue is coded #FF0000FF (or # 0000FF if yo u o mit the A lpha channel).

    0

    I







    M "

    139

    ^

    (

    5

    255

    • zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCB # FF6 S O O S B | T |

    Gr e e n V e l l n w

    /

    Hnney dew • There is a large set of named colors iHotPinfc available in Silverlight, using the I~1 I n d l a n Re d same name as the named colors in H Indigo I vnry HTML. There is a co mbo bo x Khaki belo w the co lo r sw atch that yo u FIGURE 2 .1 2 Nam ed colors. can expand to show named colors, such as in Figure 2.12. zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA

    I m p l e m e n t i n g He l l o Si l v e r l i g h t

    39

    zyxwvutsrqponm

    Using Design Tim e W idt h and Height zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF As yo u can see in Figure 2.11, the text blo ck is to o wide for the grid. In fact, neither the grid no r thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Us er Cont r ol co ntaining it have any w idth and height. If yo u check these properties in the Properties editor, yo u w ill see that they are set to Auto, w hich is the default value. It means that the element w ill resize itself to fill the available space, depending on the size of its parent, o n its co ntent, o n the alignment properties, and so fo rth. In the application we are implementing now, because the user co ntro l does no t have a size, it w ill take the size of the co ntaining obj ect tag in the HTML page. On the design surface in Visual Studio (and Expression Blend), how ever, there is no co ntainer, so the element w ould take the minimal size possible. In some cases, the auto matic w idth and height can even be zero, w hich makes it impossible to design a background, for example. To solve this pro blem, yo u can set the Des i gnWi dt h and Des i gnHei ght properties in XAML. These tw o properties are defined (along w ith a few others) in the namespace assigned to the d: prefix in the current d o cument. The interesting thing w ith d: is that all these properties w ill be igno red w hen the applicatio n is running. They w ill be applied o nly on a design surface (for example, Visual Studio designer, or Expression Blend). This is a very co nv enient help for designers, w ho can visualize w hat they create w itho ut having to run the applicatio n. You'll see mo re examples of this in Chapter 11, "Mastering Expression Blend ."

    TI P S cr u b b i n g Your X A M L

    The m echanism to ignore the attributes prefixed with d: involves two additional declarations: xm lns:m c and me: Ign or a b l e. If you decide not to use d:Desi gnHei ght or d:DesignWidt h (or any of the other d: attributes that we will talk about in this book), you can safely rem ove xm lns:d, xm lns:m c, and me: Ign ora b l e from your XAML code, as well as any attribute starting with the d: prefix.

    v

    /

    To mo d ify the design time w idth and height, yo u can either set these properties in the XAML code itself, or follow these steps:

    1. Set the cursor in the Us er Cont r ol tag in the XAML editor, or select the Us er Cont r ol in the crumb bar. 2. There is a small ico n indicating that the element is sized in design mo d e (Auto Size) or has a fixed w idth and height (Fixed Size), as show n in Figure 2.13.

    mim

    3. Resize the Us er Cont r ol in the designer. Sw itch fro m Auto Size to Fixed Size and back using the small ico n, and observe the FIGURE 2 .1 3 Auto Size and Fixed Size changes in the XAML code. zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA icons.

    40

    CH A P TER 2

    Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    Sa ving t he Applica t ion zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA In the next sectio n, we use Expression Blend to refine the applicatio n and add mo v ement to it. Because Expression Blend and Visual Studio work on the exact same files, it is imp o rtant to remember to save all the files befo re yo u mo ve from o ne env iro nment to ano ther. The easiest way in Visual Studio to save all the files (including the pro ject files) is by using File, Save All. Make sure that yo u remember w here yo u saved the application, because we w ill extend it so o n.

    Insta lling Expre ssion Blend Blend is the to o l used to visually design a Silverlight or WPF applicatio n. It is a very inno vative to o l, and might seem a little unusual to traditio nal softw are developers. To develop Silverlight 4 (or WPF 4 for that matter), yo u w ill need the new est version of Blend, named Micro so ft Expression Blend 4. You can dow nload this version fro m the Blend w ebsite, http:/ / w w w .microsoft.com/ expression. Note that there is currently no Express version of Expression Blend, o nly a co mmercial version is available. The price is $599 for a full version, part of a package called Expression Studio 4 Ultimate w ith a number of applicatio ns (including Expression Blend, Design, Web, and Encoder). If yo u have an MSDN Premium subscription, Expression Studio is included. If yo u work in a softw are d evelo pment firm, yo u should check w hether yo u have it already available!

    WARNING Ble n d 4 On ly Silverlight 4 ca n be devel oped only intoyxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB Microsoft Expression Blend 4, and not in earlier

    versions. Note, however, that the latest can be installed side by side with earlier versions. s,

    zyxwvutsrqponmlkjihgfedcba >

    We take a quick tour of Expression Blend in this chapter, before diving deeper in Chapter 11.

    Cre a t ing a Ne w Silve rlight Applica t ion W hen yo u first start Expression Blend, yo u see the W elco me screen, as show n in Figure 2.14. This screen allow s yo u to o pen an existing pro ject or create a new one, to find some help before starting, or to open preinstalled samples. If yo u close the W elco me screen, yo u can always bring it back w ith Help, W elco me Screen. The installed samples for Silverlight 4 are quite interesting because they help explain some of the capacities of Blend and of Silverlight. Do n't hesitate to explore them. You can o pen any sample and run it by pressing F5 (or selecting Project, Run Project fro m the menu).

    I n s t a l l i n g Ex p r e s s i o n B l e n d

    If yo u cho o se to create a new Silverlight 4 applicatio n, yo u must cho o se betw een a Silverlight 4 applicatio n (w ith or w itho ut w ebsite) and a Silverlight 4 co ntro l library, used to ho st co ntro ls that can be included in multiple applicatio ns. Just like in Visual Studio, selecting Silverlight 4 A pplication + Website w ill create an ASP.NET w eb applicatio n pro ject w ith a link to the actual Silverlight applicatio n. Note, how ever, the follow ing:

    Pr o j e c t s

    41

    zyxwvutsrqponmlkj

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJ H e l p zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO Samples

    Si I v e r l i g h t C o m r o I L i b r a r y l W p f Ap p l i cation 1 Si I ve r l i g h t A p p l i c a t i o n * ! Si I v e r l i g h t A p p I i c a t i o n 3 Si I v e r l i g h t A p p I i c a t i o n 2

    • In Expression Blend, yo u do no t have the cho ice betw een ASP.NET Web A pplication, Website, or ASP.NET MVC. • If yo u create a Silverlight applicatio n w itho ut a ho sting w ebsite, yo u canno t add this applicatio n to ano ther w ebsite in Blend. You also canno t create a new w ebsite in Blend w itho ut an attached Silverlight applicatio n.

    New

    [ f i

    Pro je c t...

    Op en

    Proj ect ...

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPON

    Iv^Run at startup

    FIGURE 2 .1 4 screen.

    Expression Blend Welcom e

    If yo u need mo re extended o ptio ns w hen creating your applicatio n, yo u need to create it in Visual Studio. Because Expression Blend and Visual Studio use exactly the same solutio n files, pro ject files, and code file, yo u can create an applicatio n in the enviro nment of your cho ice and then mo d ify it somew here else. You can even open the pro jects in bo th enviro nments at the same time, as yo u w ill see in Chapter 11 w hich is especially useful w hen yo u do design work on your applicatio n's screens.

    Opening Hello Silve rlight We w ill refine our Hello Silverlight applicatio n and add some mo v ement and effects. This is the perfect task for Expression Blend: Even tho ugh mo st of w hat yo u can do in Blend can also be d o ne in Visual Studio (and vice versa), Blend is mo re suitable for design tasks, and Visual Studio for d evelo pment tasks. It is really up to yo u to cho o se the to o l that suits yo u the best. To refine the applicatio n we created earlier in this chapter, follow these steps: 1. Select Open Pro ject fro m the W elco me screen show n in Figure 2.14, or w ith cho o se File, Open Project/ Solution fro m the menu. 2. Navigate to the folder in w hich yo u last saved the Hello Silverlight applicatio n. 3. Select the so lutio n file HelloSilverlight.sln and o pen it in Blend.

    42

    CH A P TER 2

    Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

    Using Sh ort cu t s t o Ope n a Solut ion in Ble nd from Visua l St udio

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO

    This w ay of o pening an application is a bit slow, and there are ways to speed things up, by selecting o ne of the alternatives: • In Visual Studio, right-click a XAML file, and select Open in Expression Blend from the co ntext menu. This w ill start Blend and o pen the so lutio n.

    WARNING Ch o o si n g t h e R i gh t Ve rsion

    If you have Blend 3 and 4 installed side by side, chances are that the Open in Expression Blend context m enu will pick the wrong version. In som e cases, the m enu m ight even be m issing altogether. To correct t his, refer to Tim Heuer's blog: http:/ / www.galasoft.ch/ sl4 -integration.

    • Right-click the so lutio n in the So lutio n Explorer, and select Open Folder in Windo w s Explorer. Then in Window s Explorer, right-click the so lutio n HelloSilverlight.sln and select Open W ith, Micro so ft Expression Blend 4 from the Windo w s Explorer co ntext menu.

    Using Sh ort cu t s t o Ope n a Solut ion in Visua l St udio from Ble nd

    The same sho rtcut exists fro m Expression Blend, to o : In Expression Blend, right-click the so lutio n file, any pro ject file, or any code file in the Projects panel, and select Edit in Visual Studio fro m the co ntext menu. After o pening the so lutio n and MainPage.xaml in Blend, yo u sho uld be no w seeing the exact same scene as in Visual Studio's designer. Only a few adorners are different. The design time w idthzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA ( d: Des i gnWi dt h) and height ( d: Des i gnHei ght ) are also ho no red in Expression Blend!

    Adding an Effe ct We w ill no w add a shadow effect to the Hello Silverlight text blo ck. To do this, follow these steps:

    1. Locate the Text Bl ock in the Objects and Timeline panel. This panel displays the tree of all the elements on the page, as show n in Figure 2.15: The Us er Cont r ol (the page) co ntains a Gr i d, w hich co ntains a Text Bl ock.

    Objects and Timefine ^ X {No Stoiyboord open) yxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB -±- [UserControl]

    mm

    » -t* [UserControl] » is LayoutKoot

    FIGURE 2 .1 5

    2. Select the Text Bl ock and then co py and paste it. You can use the co ntext menu for that, or Ctrl+C, Ctrl+V.

    «&

    o I

    The elem ents t ree.

    I n s t a l l i n g Ex p r e s s i o n B l e n d

    43

    Click tw ice slow ly on the first Text Bl ock in the tree to make its name editable, and 3.zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA change the name to zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA Shadow. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    TI P W o r k i n g in Ble n d, W o r k i n g in X A M L

    Just as with the Visual Studio designer, everything we do in Blend is im m ediately reflected in the XAML code: Open the page in split m ode, using the Split button located on the top right of the m ain panel, as show in Figure 2 .1 6 . Then press Ctrl+Z to cancel the last operation, and then Ctrl+Y to repeat it. Observe how the XAML code is m odified by Blend. \

    You should no w see tw o text blo cks in the Objects and Timeline panel: One is named Shadow, and the seco nd do esn't have a name. However, bo th have exactly the same features, and therefo re the fro nt o ne is hiding the back o ne in the designer. Let's change this w ith the next steps:

    El pal FIGURE 2 .1 6

    Using the Split button.

    TI P Un d e r st a n d i n g t h e Z -Or d e r

    Because the order in the tree reflects the order in which objects appear in the docum ent, the Shadow (higher in the tree) appears behind the nam eless Text Bl ock . \

    /

    1. Select the Shadow element in the Objects and Timeline panel. 2. Make sure that the Properties panel is

    selected on the right side of the w indow , and using the brush editor, change the Shadow 's foreground to black, as show n on Figure 2.17. 3. On the left of Blend's w indow , yo u

    sho uld see the tabs Projects, Assets, States, and Parts. You'll learn mo re about all the panels in Chapter 11. For now, select the Assets tab. This is w here yo u w ill find all the co ntro ls and effects that we can use in Silverlight. 4. Select the Effects category. You w ill see the tw o built-in effects in Silverlight 4: Bl u r

    and DropShadow.

    44

    CH A P TER 2

    Se t t i n g Up a n d D i s c o v e r i n g Yo u r En v i r o n m e n t

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    TI P Loa ding Ad d i t i on a l Ef f e ct s, P e rf orm a n ce

    Effects in Silverlight 4 are rendered by sm all com ponents called yxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB pixel shaders. Although the default installation of Silverlight contains only two effects, you can find m ore online and add them to your application, as you will see in Chapter 16 "Using Effects and Recording Media." For this effect, we will use a Bl u r effect applied to the Text Bl ock in the background. Note that we could also use the DropShadow effect available in Blend. However the DropShadow effect is slower than the Bl u r effect; if you can, it is recom m ended to use a Bl u r effect instead, as we do here. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    >. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    5. Select the Bl ur effect and drag/ drop it w ith the mo use o n the Shadow Text Bl ock in the Objects and Timeline panel, as in Figure 2.18. 6. W ith the Bl ur Ef f ect selected in Obj pr t s a n d Tim pllnp wtsrqponmlkihedcaXTSCA * X (No Sto iy baûrd o p en} V X . the Objects and Timeline panel, [ UserCont roQ check the Properties panel on the O m right of the w indow , and set the » [UserCo ntro l] Radi us property to 40. You should * 15 Lay out Root ® no w see a shadow right behind the Ml Sh ad ow k Hello Silverlight Text Bl ock. zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA +

    Cre a t ing a Pulse Anim a tion We w ill no w add some mo v ement to the scene, by animating the Shadow w hen the Text Bl ock is clicked. Follow these steps:

    FIGURE 2 .1 8 effect.

    Dragging and dropping the blur

    1. In the Objects and Timeline panel show n in Figure 2.18, click the small plus sign (+) lo cated on the to p right of the panel to create a new storyboard. zyxwvutsrqponmlkjihgfedcbaYWVUT 2. In the Create Storyboard Resource dialog, name the storyboard ShadowStoryboard.

    3. No tice ho w Blend turns in animatio n recording mo de, w ith a red border signifying that the actio ns yo u perform no w on the scene w ill be part of the storyboard.

    TI P M o r e Ab o u t S t o r yb o a r d s a nd An i m a t i o n s

    For m ore inform ation about st oryboards and anim ations, you can jum p into Chapter 3 of Silverlight

    2

    Unleashed.

    v 4. Mo ve the yellow vertical line (called the timeline) to 500 milliseco nds, as show n in

    Figure 2.19.

    5. Select the Shadow Text Bl ock.

    I n s t a l l i n g Ex p r e s s i o n B l e n d

    6. Click the Record Keyframe butto n. This butto n is circled in orange in Figure 2.19.

    Objects and Timeline o SlMduwSluiybudii -i. [UserControl]

    *

    H C o m m o n Siiv er lTg h t Co n t r o l s |> A l l Sr l v er i i g h t Co n t r o l s , ==, and and < signs to " > ; " and " &l t ; ", respectively to avoid errors in the XML d o cument. • The last child is ano ther Text Bl ock used to display the Thr es hol d property, again thro ug h a Bi ndi ng o n the Te mpl a t e dPa r e nt .

    • Finally, in the third co lumn (set by Gr i d. Col umn="2") , we have a red Bor der named I ncr ement Par t , ano ther meaningful name for the Thr e s hol dCont r ol . zyxwvutsrqponmlkjihgfedcbaZYXWV

    Re pre se nt ing the Visua l St a t e s

    This co ntro l template does no t take care of the co ntro l's state. Ideally, we w ant the three Text Bl ock instances w ith to be show n or hidden according to the state of the co ntro l. To do this, we w ill mo d ify the template according to the Hi gh, Equal , and Low states. Add the XAML code in Listing 3.19 w ithin the main Bor der tag (w hich is betw een lines 4 and 5 of Listing 3.18).

    72

    CHAPTER 3

    L I STI N G 3 . 1 9

    1

    Ext e n d i n g You r Ap p l i ca t i o n w i t h Co n t r o l s

    Set t i ng t he Cont rol Tem plat e's High St at e

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF

    2

    3

    4

    5

    8

    10

    11

    14

    16

    17

    18

    19

    20

    21



    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF

    The Vi s ua l St a t e Gr oup tag o n line 3 g ro up s all the states b elo ng ing to o ne g ro up

    (in

    this case, the Thr e s hol d state g ro up ). •

    O n lines 3 to 18, w e d efine a transitio n (in the fo rm o f a St or yboa r d) fro m any state to the Hi gh state. Tw o elem ents are targ eted : The Equa l Te xt Bl oc k and the

    LowTe xt Bl oc k are hid d en. Fo r exam p le, the Equa l Te xt Bl oc k 's Opa c i t y is set to 0 o n lines 5 to 10, at a Ke yTi me o f 0 seco nd s. This m eans that the transitio n is im m ed iate. Yo u co uld sp ecify a d ifferent Ke yTi me (fo r exam p le, " 0: 0: 0. 2" , w hic h is 200 milliseco nd s) to hav e a sm o o ther transitio n. •

    O nly the Hi gh state is rep resented in Listing 3.19. The o ther states ( Equal and Low) are v ery similar and sho uld ap p ear instead o f the XM L c o m m e n t at line 19. The c o m p lete so urce co d e is av ailable at http :/ / galaso ft.ch/ SL4U/ Co d e/ Chap ter03.

    As y o u can see in this chap ter, creating c o ntro l tem p lates in Visual Stud io is n o t an easy task, because o f the am o u n t o f XA M L co d e that is inv o lv ed . Ev en a v ery simp le tem p late like the Th r e s h o l d Co n t r o l 's d efault tem p late requires a lo t o f m anu al w o rk. This is w h y c o ntro l tem p lates are ty p ically created in Exp ressio n Blend , w hic h is a fantastic to o l fo r this kind o f w o rk.

    Su m m a r y

    73

    Sum m a ry zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA In this chapter, we discussed the extensibility of XAML documents, w hich is very useful to import all kind of objects into your user interface, from simple values to objects in resources to controls. Then we discussed user controls, and how they are used to group and encapsulate other controls. With user controls, you can easily divide your user interface in smaller, more manageable pieces. You can also reuse these pieces in multiple places in your application. And of course, you can also add properties w ithin to extend the user control's functionality. Finally, we studied custom controls, w hat Silverlight coders call "lookless controls". These controls enforce a strict separation of functio nality (in the code) and presentation (in a control template). The code is typically developed and tested by a developer, w hile someone in the role of a designer works on the template. In this Chapter we saw how to create a default template, useful to test the control's functionalities. In Chapter 10, we will see how more elaborate and complex templates can be created for existing controls.

    zyxwvutsrqponm

    This page intentionally left blank

    CH A P TER

    4

    Investigating Existing Co ntro ls

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML I N TH I S CH A P TER , W E W I LL: •

    Review som e controls tha t were discussed in Silverlight 2 Unlea shed, and tha t are still present and useful in Silverlight 4 .

    • See wha t cha nges Silverlight 4 brought to e xisting controls.

    I n Chapter 3, "Extend ing Your A pplication w ith Co ntro ls," yo u saw ho w to create user co ntro ls and custo m co ntro ls to extend your applicatio n w ith functio nality. However, in many cases, yo u do no t actually need to create co ntro ls yourself. Instead, yo u w ill use existing co ntro ls, either w ithin the Silverlight framew ork itself or from external providers. In this chapter, we cover these controls, including w hat has changed since Silverlight 2 was released and w here to find new co ntro ls.

    Re vie wing the Ba sics



    Talk about new controls added to the core Silverlight fram ework.



    Explore the Silverlight Toolkit, a collection of controls provided by M icrosoft independently from the core Silverlight fram ework.



    List som e points tha t you should che ck before purchasing controls from third-pa rty vendors. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSR

    InzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed, we spent tw o chapters talking about co ntro ls. First, we review ed the Silverlight class hierarchy in Chapter 15. Understanding ho w o bjects and co ntro ls are co mpo sed is very impo rtant to master the framew ork. Further in the same chapter, we talked about panels (such aszyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA St ackPanel , Canvas , and Gr i d) , and w hen yo u should be cho o sing w hich panel to layout your applicatio n. We also spent some time talking about Scr ol l Vi ewer and Popup, and finished w ith a section about the Shape class (such as Rect angl e, El l i ps e and Pat h) . Then, in Chapter 16 of Silverlight 2 Unleashed, we talked about the properties of the Cont r ol class, befo re review ing some of the co ntro ls: • The Text Bl ock, used to present and fo rmat text. • The Text Box, used to let the user input and edit text. • The But t on, CheckBox, Radi oBut t on, Hyper l i nkBut t on, Repeat But t on, and Toggl eBut t on, all deriving from the But t onBas e class used for all things that can be clicked.

    76

    CH A P TER 4



    I n ve s t i g a t i n g Exi s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED

    Scr ol l bar zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA and Sl i der , two controls similar in the way they are built, bo th w ith a middle element that can be dragged along a track. The Scr ol l bar is used to scroll big areas, w hile the Sl i der is used to set a value (in steps or continuously) by dragging their middle part. We also talked about the Thumb control, very useful w hen you need something you can drag.

    • The Gr i dSpl i t t er that can be dragged to resize a grid's cells. • The Cal endar and Dat ePi cker controls, useful to input and edit dates in an applicatio n. • The I nkPr es ent er , a control that is used to allow the user to draw or write on the screen, ideally w ith a stylus or his fingers. We then proceeded w ith an introduction to the I t ems Cont r ol (of w hich most data controls derive, such as TabCont r ol , Li s t Box, ComboBox, and so on). The chapter ended w ith a section about DeepZoom, an impressive feature that allows smooth zooming into high-definition pictures, allowing a fantastic experience such as demonstrated in the Matterhorn demo we sampled earlier. A nother good chapter inzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed about controls is Chapter 18, specifically the second half about data controls: • That chapter covers how to use the Li s t Box, one of the most useful controls in the w hole Silverlight framework to represent collections of data. • We worked w ith the Obs er vabl eCol l ect i on class, a class made to ho ld a list of items and notify its users (for example, a data control) w hen items are added, removed, or w hen the order of these items changes. • We studied the Dat aGr i d, a powerful element to display, sort, group, filter, and edit data in business applications. Few changes were made to all these controls since Silverlight 2 was released. It must be no ted that all the controls that were into the Silverlight 2 Toolkit are now included into the code framework. In this chapter, we review changes that were made to existing controls, and we will talk about some of the new controls that were included in Silverlight 3 and 4. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Show M e Som e Code ! To illustrate the features mentio ned in this chapter, a sample browser can be downloaded from http:/ / www.galasoft.ch/ SL4U/ code/ chapter04. The application uses sample data created by Expression Blend (a feature that we discuss in Chapter 11, "Mastering Expression Blend"). This is especially interesting w hen working w ith data controls because Blend creates a list of random items w ithout the developer having to come up w ith complicated services or XML files. A nother interesting feature of

    Ch a n g e s in Exi st i n g Co n t r o l s

    77

    zyxwvutsrqponml

    this Silverlight applicatio n is a navigatio n application, a special type of applicatio n that we w ill review in Chapter 15, "Develo ping Navigation A pplications and Silverlight for Window s Pho ne 7." In this sample applicatio n, we use thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Cus t omer s co llectio n in multiple samples. This co llectio n (defined by Blend as a static resource in A pp.xaml) has a number of customers d efined , each w ith a Na me ( s t r i ng) , Cont r a c t Numbe r ( i nt eger ) , and I s Ac t i ve ( bool ) pro perties. Expression Blend generated the values. For instance, the XAML code in Listing 4.1 binds a co ntro l's Cur r ent l t em property to the first customer in the co llectio n. In Listing 4.2, we bind a data co ntro l's I t ems Sour ce property to the list of customers. LISTING 4 .1

    Binding to the First Cust om er

    Cur r e nt l t e m=" {Bi ndi ng Sour c e ={St a t i c Re s our c e Cus t ome r s }, Pa t h=Col l e c t i on[ 0] }" / >

    LISTING 4 .2

    Binding to the List of Cust om ers

    I t e ms Sour c e =" {Bi ndi ng Sour c e ={St a t i c Re s our c e Cus t ome r s }, Pa t h=Col l e c t i on}" zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Cha nge s in Exist ing Controls All the co ntro ls that were available in Silverlight 2 and 3 are still available in Silverlight 4. There were a few changes to existing controls, tho ugh.

    M ouse W he e l Support The co ntro ls w ith a co ntent that can be scrolled no w auto matically support the mo use w heel actio n. The co ntro ls in questio n are as follow s: •



    Sc r ol l Vi e we r

    Text Box (o nly w hen the Ver t i cal Scr ol l Bar Vi s i bi l i t y property is set to Aut o or Vi s i bl e )



    ComboBox (w hen the number of items is large eno ugh)



    Cal endar (to scroll the decades, years, mo nths)



    Dat ePi cker (to scroll the decades, years, mo nths w hen the Cal endar is o pen)

    Loca lizing for Right-to-Le ft La ngua ge s The story of localizing Silverlight applicatio ns is no t perfect by a long shot, but a step in the right direction was taken w ith the intro d uctio n of support for right-to -left languages (for example, Hebraic or Arabic languages). Simply set the Fl owDi r ect i on property on any Fr amewor kEl ement to Ri ght ToLef t for such languages. The default is Lef t ToRi ght .

    78

    CH A P TER 4

    I n ve s t i g a t i n g Exi s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    Ge t t ing a Cont rol Te m pla te 's Curre nt St a t e zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML

    A co ntro l's template typically defines various state groups w ith states and transitio ns, as yo u saw in Chapter 3, "Extend ing Your A pplication w ith Co ntro ls." For example, azyxwvutsrqponmlkjihgfedcbaZYXW But t on has th e states Nor ma l , Mous e ove r , Pr e s s e d an d Di s a bl e d (in th e state g ro u p CommonSt a t e s ) ,

    and can transitio n from o ne to the other. However, getting the co ntro l's current state pro grammatically was difficult, because neither the co ntro l no r the Vi s ual St at eManager class keeps track of w hich state the co ntro l currently is in. It is possible to build a custo m class deriving fro m Vi s ual St at eManager and to assign it using Vi s ual St at eManager . Set Cus t omVi s ual St at eManager static metho d . However, for small applications, this is to o co mplex. In Silverlight 4, this is corrected, w ith the addition of the Vi s ual St at eGr oup. Cur r ent St at e property. Getting a co ntro l's current state to calculate the next transitio n in code is show n in Listing 4.3. This makes calculating the transitio ns easier because keeping track of the current state is no t needed anymo re. LISTING 4. 3 1

    va r

    2 4

    if

    10

    ( gr oups == nul l \\ g r o u p s . Co u n t

    == O)

    {

    7

    8

    gr oups = Vi s u a l St a t e Ma n a g e r . Ge t Vi s u a l St a t e Gr o u p s ( b a c k g r o u n d ) ;

    5

    6

    Getting a Control's State

    r e t ur n;

    } Vi s u a l St a t e Gr o u p gr oup

    11

    = gr oups [ 0]

    13

    if

    14

    {

    15

    a s Vi s u a l St a t e Gr o u p ;

    ( gr oup == nul l ) r e t ur n;

    16

    }

    18

    Vi s u a l St a t e c u r r e n t St a t e = g r o u p . Cu r r e n t St a t e ;

    20

    / / Ca l c ul a t e t r a ns i t i on ba s e d on c ur r e nt

    s t at e

    • On line 2, the variable backgr ound is a Fr amewor kEl ement that is part of the co ntro l template, and on w hich the visual states are defined in XAML (as we did, for example, in Listing 3.19).

    Ch a n g e s in Exi st i n g Co n t r o l s

    79

    zyxwvutsrqponml

    • Note that depending on ho w the co ntro l template is built, a givenzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ Vi s ual St at eGr oup or a given state w ithin that group might no t be available. The code should take this fact into acco unt, and be robust eno ugh no t to crash if that is the case, as in Listing 4.3 on lines 4 to 8. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    AddingzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Se l e ct e d Val u e and Se l e ct e d Val u e Pat h All co ntro ls deriving fro m the Sel ect or class no w have tw o new properties: Sel ect edVal ue and Sel ect edVal uePat h. In the Silverlight core framew ork, tw o co ntro ls derive fro m Se l e c t or : ComboBox and Li s t Box. These properties w ork to gether to facilitate data bind ing in XAML. For instance, imagine that a Li s t Box displays a list of customers. Each Cus t omer item has a Name property and a Cont r act Number property. The Li s t Box is set to display the customer's name. However, by setting the property Sel ect edVal uePat h to " Cont r act Number " , yo u can then bind to the Li s t Box 's Sel ect edVal ue property, as show n in Listing 4.4. Note that ano ther w ay to reach the exact same result w ould be to bind to the Li s t Box 's Sel ect edl t em. Cont r act Number , as show n in Listing 4.5. Bo th expressions work the same. However, Sel ect edVal uePat h and Sel ect edVal ue are invaluable w hen all yo u have to identify the bind ing is a set of strings (for example, from a ComboBox, fro m a w eb service, or fro m a database). LISTING 4 .4

    Using SelectedValue and SelectedValuePath



  • Using Se l e ct e d l t e m



  • Adding Command and CommandParamet er Co mmand s were intro duced in Windo w s Presentatio n Fo undatio n (WPF) fro m the first version to imp lement a loosely coupled event-hand ling mechanism. W hen yo u implement an event hand ler for a But t on co ntro l, for example, yo u create a very strong link betw een the XAML and the code behind . This can cause unexpected side effects, such as

    80

    CH A P TER 4

    I n ve s t i g a t i n g Exi s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    memo ry leaks, especially if you forget to unregister the event handler w hen thezyxwvutsrqponmlkjihgfedcbaZYXWVU But t on is disposed. You'll learn more about this in Chapter 21, "Optimizing Perfo rmance." A nother anno ying effect w ith events is that the event handler must be located in the code behind . That can be an issue, especially w hen you create a template: Generally, the template is located in a resource dictio nary that does no t have any code behind (as you w ill see in Chapter 10, "Creating Resources, Styles, and Templates"). Using events creates a strong dependency betw een the XAML and the code behind that co mplicates the work of the designers. To solve this issue, instead of a Cl i ck event, you can use the Command property (and an o ptio nal CommandPar amet er property) that w ill invoke a metho d on an o bject, no t necessarily in the page's code behind . Note that the o bject must implement the I Command interface that was already available in Silverlight 2 and Silverlight 3. Until Silverlight 4 was released, it was quite difficult to use co mmand s in Silverlight because mo st of the infrastructure was missing and a lo t of manual work was involved. In Silverlight 4, how ever, we get (almost) the same support as in WPF, w ith the addition of th e Comma nd and Co mma n d Pa r a me t e r p ro p erties o n th e But t onBa s e class (o f w h i c h But t on,

    Re pe a t But t on, Toggl e But t on, Che c kBox, Ra d i o Bu t t o n d eriv e) and o n th e Hy p e r l i n k Bu t t o n

    co ntro l. You'll learn more about co mmand s in Chapter 7, "Understanding the Model-ViewView Model Pattern." A short example is provided in the sample browser available at http:/ / www.galasoft.ch/ SL4U/ code/ chapter04. Listing 4.6 shows the C# code w ith the I Command implementatio n, and the o bject that holds a property of this type. In Listing 4.7, yo u can see the XAML code that binds a But t on 's Command property and its CommandPar amet er o n the corresponding o bjects. The I Command interface specifies three compulsory members: • The Execut e metho d is called w hen the co mmand is invoked. For the co ntro ls that have the Command property, clicking the co ntro l is the o nly w ay to actually invoke the co mmand . In Chapter 19, "A uthenticatio n, Event to Co mmand Binding, Random A nimations, Multito uch, Local Co mmunicatio n, and Bing Maps Co ntro l," yo u will see other ways to invoke a co mmand , w itho ut being limited to clicking the co ntro l. Note that the Execut e metho d has a parameter (of type obj ect ) . This parameter holds the value of the CommandPar amet er property on the invoking co ntro l. If CommandPar amet er is no t set, then the parameter is nul l . • The CanExecut e metho d should return t r ue if the co mmand may be invoked, and f al s e otherw ise, depending on the value of the CommandPar amet er or of any other influencing factors. The co ntro l that the co mmand is bo und to will be enabled/ disabled auto matically according to the value returned by this metho d . • The CanExecut eChanged event must be raised w hen the value of the CanExecut e metho d changes. For example, imagine that the value of CanExecut e depends on the value of an o bject's property. W hen this property changes, the CanExecut eChanged event must be raised manually to no tify the user interface that CanExecut e must be queried, and the co ntro ls enabled/ disabled accordingly.

    Ch a n g e s in Exi st i n g Co n t r o l s

    81

    W A R N I N G zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Ra isingyxwvutsrponmlkihgfedcbaYWVUTSRPONMLIHGFEDCBA CanExecuteChanged M a nua lly zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Devel oper s us e d t o WP F wi l l f i nd puzzl i ng t hat t he Ca nExe c ut e Cha nge d e ve n mu s t be r ai s ed manual l y i n Si l verl i ght . In t he r i cher WPF, a cl as s n a me d Comma ndMa na ge r t a ke s car e of quer yi ng all t he c o mma n d s wh e n s ome t hi ng ha ppe ns i n t he us er i nt er f ace (for e xa mpl e , wh e n a us er ent er s t ext , cl i cks a n i t em, a nd s o on) . In Si l verl i ght , t hi s s uppor t doe s not exi st . zyxwvutsrqponmlkjihgfedcbaZ

    V

    /

    L I STI N G 4 . 6

    Im plem ent ing a Com m and and Usi ng It as Propert y

    1

    publ i c c l a s s Re c e i ve Va l ue Comma nd : I Comma nd,

    2

    {

    I Not i f yPr ope r t yCha nge d

    3 4

    publ i c e ve nt Eve nt Ha ndl e r Ca nExe c ut e Cha nge d; publ i c e ve nt Pr ope r t yCha nge dEve nt Ha ndl e r Pr ope r t yCha nge d;

    6

    publ i c s t r i ng Re c e i ve dVa l ue

    7

    {

    8 9

    ge t ; pr i va t e s et ;

    10

    }

    12 13 14 15 16

    publ i c bool Ca nExe c ut e ( obj e c t pa r a me t e r ) { / / Ent e r i ng t he wor ds " Hel l o Wor l d" wi l l di s a bl e t he c omma nd! r e t ur n pa r a me t e r ! = nul l && pa r a me t e r . ToSt r i ngO ! = " Hel l o Wor l d" ;

    17

    }

    19

    publ i c voi d Exe c ut e ( obj e c t

    20

    {

    pa r a me t e r )

    zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDC

    21 22 23 24 25 26 27 28 29

    / / Comma nd wa s i nvoke d i f ( pa r a me t e r == nul l ) { Re c e i ve dVa l ue = " Nul l " ; } el s e { Re c e i ve dVa l ue = pa r a me t e r . ToSt r i ngO ; }

    31 32 33 34 35

    / / Not i f y t he bi ndi ngs i f ( Pr ope r t yCha nge d ! = nul l ) { Pr ope r t yCha nge d( t hi s , new Pr ope r t yCha nge dEve nt Ar gs ( " Re c e i ve dVa l ue " ) ) ;

    82

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA 107 CH A P TER 4 I n ve s t i g a t i n g Exi s t i n g Co n t r o l s zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    }

    36 37

    }

    38 39 40 41

    publ i c c l a s s {

    Co mma n d Sa mp l e Vi e wMo d e l

    42

    publ i c I Comma nd Re c e i v e Co mma n d

    43

    { get;

    44 45 46

    pr i va t e s e t ;

    }

    47 48

    publ i c

    49

    {

    50 51

    Co mma n d Sa mp l e Vi e wMo d e l ( )

    Re c e i v e Co mma n d = ne w Re c e i v e Va l u e Co mma n d ( ) ;

    }

    52

    • Line 3 declares the CanExecut eChanged event, as required by the I Command interface. • Note that the co mmand also implements I Not i f yPr oper t yChanged. (Defined on line 1, and implemented on line 4, this interface defines only one event, Pr oper t yChanged. We will raise this event a little later.) This is useful because we w ant to use data binding on the Recei vedVal ue property. However, having a co mmand implementing I Not i f yPr oper t yChanged is a little unusual. We discuss better alternatives in Chapter 7. • Lines 6 to 10 define a custom property that will store the value received w hen the Execut e metho d is invoked, depending on the CommandPar amet er property on the But t on control. • Lines 12 to 17 define the CanExecut e metho d that is executed w hen the co mmand is bo und to a control, each time that the CanExecut eChanged event is raised, or every time that the CommandPar amet er property's value changes. For example, in Listing 4.7, Co mma n d Pa r a me t e r is b o u n d to th e Va l u e Te x t Bo x . Te x t p ro p erty , so Ca n Ex e c u t e

    will be executed w hen the user types something in the Val ueText Box. • Lines 19 to 37 declare the Execut e method, also required by the I Command interface. This metho d simply stores the string value of the parameter into the Recei vedVal ue property. • On lines 32 to 36, we raise the Pr oper t yChanged event, thus notifying subscribers (for example, data bindings) that the Recei vedVal ue property changed. First we check w hether the event is nul l (w hich would be the case if no bo dy subscribed to the event).

    Ch a n g e s in Exi st i n g Co n t r o l s



    83

    Fro m line 40, w e d eclare a new class, called zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Comma ndSa mpl e Vi e wMode l . This class is the zyxwvutsrqponmlkjihgf fo r the Comma ndSa mpl e p age (also called the view). This is a simp le im p le-

    viewmodel

    m e ntatio n o f the M o d el-V iew -V iew M o d el p attern, w hic h w e co v er in m o re d etail in Chap ter 7. •

    Lines 42 to 46 d eclare a p ro p erty o f ty p e I Comma nd. The p ro p erty is instantiated at line 50, b y creating a new Re c e i ve Va l ue Comma nd. W e w ill b in d the But t on 's Comma nd p ro p erty to this I Comma nd in Listing 4.7.

    L I STI N G 4 . 7

    1 2

    Usi n g t he Com m a n d in XAM L





    />

    O n line 2, w e create a new instanc e o f the Comma ndSa mpl e Vi e wMode l class in the

    Us e r Cont r ol 's reso urces. Rem em b er that reso urces are a sto re w here y o u can keep any kind o f o b jec t, n o t just styles and tem p lates. In this case, the vm p refix is m ap p ed to the CLR nam esp ac e Si l ve r l i ght Tool ki t Sa mpl e s . Vi e wMode l , w here this class lives. Th e n o n line 6, w e assign the instanc e o f Comma ndSa mpl e Vi e wMode l to the St a c kPa ne l 's Da t a Cont e xt . Fro m n o w o n, the so urce fo r ev ery Bi ndi ng w ill im p lic itly b e that instance, unless o f co urse y o u sp ecify o therw ise exp licitly . Lines 11 and 12 d efine a Te xt Box nam e d Va l ue Te xt Box. W e w ill use this as the so urce fo r the Comma ndPa r a me t e r . Further, line 15 assigns the Re c e i ve Comma nd p ro p erty fro m the

    Comma ndSa mpl e Vi e wMode l instanc e to the Comma nd p ro p erty o f the But t on. Because w e d o n o t d efine any so urce fo r this Bi ndi ng, it au to m atic ally refers to the Comma ndSa mpl e Vi e wMode l instanc e that w e set as Da t a Cont e xt .

    84

    CHAPTER 4

    In ve st i ga t i n g Exi st i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    Line 16 assigns thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Te xt p ro p erty o f Va l ue Te xt Box to the Cor wi a ndPa r a me t e r o f the But t on.

    We explicitly set the Bi ndi ng 's source (through the El ement Name) to be the Text Box. In that case, the Bi ndi ng 's source is no t the Dat aCont ext . Finally, line 19 displays Recei veCommand 's Recei vedVal ue property into a Text Bl ock. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Pre se nting and Editing Te xt wit h the Ri c hTe xt Box Until Silverlight 4 was released, the possibilities to present and edit rich text were quite limited. For presentatio n, it was possible to co mbine to gether some Text Bl ock elements w ith different fo rmatting, but this was cumberso me. For rich text edition, no thing was available out of the bo x. In Silverlight 4, the Ri chText Box co ntro l was intro duced to provide such a support, w ith the follow ing features: • The Ri chText Box co ntains a co llectio n of Bl ock instances. These can be simple paragraphs, or fo rmatted blo cks such as Bol d, I t al i c, and Under l i ne. These elements can also be co mbined . • You can add any element deriving fro m UI El ement (such as shapes, images, panels, co ntro ls, and so on), using an I nl i neUI Cont ai ner w rapping it. • The Ri chText Bl ock provides the possibility to include Hyper l i nks for navigatio n to w eb pages. However, the Hyper l i nks are active o nly w hen the Ri chText Bl ock is in read-o nly mo d e. • Static text is fo rmatted using XAML, as show n in Listing 4.8. Of course, as always in Silverlight, everything that can be d o ne in XAML can also be d o ne in code, w hich allow s for d ynamic fo rmatting of the Ri chText Box 's co ntent. • The Ri chText Box 's Xaml property gives access to the fo rmatted rich co ntent expressed as XAML. This offers a co nv enient w ay to save the co ntent of the bo x in a file, or to set it later.

    LISTING 4 .8

    RichTextBox with Rich Content



    Zo o m i n g w i t h t h e Vi e w b o x

    Si l v e r l i g h t br ows e r

    i s a c r o s s - b r o ws e r ,

    p l u g - i n t ha t

    85

    zyxwvutsrqponmlkji

    c r o s s - p l a t f o r m a nd c r o s s - d e v i c e

    he l ps c ompa ni e s de s i gn,

    de l i ve r a p p l i c a t i o n s a nd e x p e r i e n c e s on t he We b.

    de ve l op a nd

    Go t o

    Si l v e r l i g h t . n e t t o l e a r n mor e !





    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Note the follow ing: • Setting properties on the Ri chText Box itself will make these valid for the w hole co ntent. You can overload these properties (for example, the Font Si ze property) on an inner element. • Notice the usage of the Run element to make a w hole paragraph bold, and of the Bol d element to make parts of the paragraph bold. You can combine these elements and others to achieve the desired formatting. • As mentioned, the I nl i neUI Cont ai ner element can be used to add any UI El ement to the co ntent. The sample available at http:/ / www.galasoft.ch/ SL4U/ code/ chapter04 also shows a Medi aEl ement playing a video. • By default, the Ri chText Box does no t display any scrollbars, even if it is resized smaller than its co ntent. Use the Ver t i cal Scr ol l Bar Vi s i bi l i t y and Hor i zont al Scr ol l Bar Vi s i bi l i t y properties to change this.

    Using these features, and w ith some code involved, it is possible to provide rich editing capabilities to your Silverlight application's users. A co mmo n usage for the Ri chText Box is to combine it w ith a custom toolbar to format parts of the text and to add rich elements. zyxwvutsrqponmlkjihgfe

    Zoom ing wit h the Vi e wbox The Vi ewbox is a fantastic control w hen you need to zoom an area (or all) of your Silverlight application, or w hen you need to scale an element that was no t made for it (for example a Pat h) . For example, suppose that you w ant your application to fill the entire HTML host, whatever the size of this host is. This can be quite tricky and involve a lot of calculation and layout. However, in certain cases, it is much easier to design your application for a given size, and then to scale it up or down to fill the w hole space.

    86

    CH A P TER 4

    I n v e s t i g a t i n g Ex i s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    TI P W a t ch i n g N e t f lix w i t h Si l ve rl i gh t

    Our readers in the United States have probably heard of Netflix, the well-known DVD rental service. Netflix also has a stream ing service over the Internet: Browse the list of available streamed online: It is m ovies, select the one you like, and watch it instantly. The m ovie isyxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB sent over the wire, buffered on the client com puter, and as soon as enough of it is available, it st art s playing. The Netflix application in Windows Media Center (on Windows 7) is scaled up or down depending on the size of the containing window. The application always looks proportional, whatever the size of the container, as shown in Figure 4 .1 . zyxwvutsrqponmlkjihgfedcbaZYXWVUTSR

    v To scale your application and fill the w ho le ho st, follow these steps: 1. Open your Silverlight applicatio n in Visual Studio or in Expression Blend. 2. Set a fixed size on the main panel. For example, yo u may w ant to design your applicatio n for a standard mo nito r size, such as 1024 x 768 pixels.

    Desperado (1995)

    zyxwvutsrqponmlkjihgfedcbaZYXW

    This bo ulh-o Mhp• bordpr artio n llark. pick* up wtipre the* «nrli h it El M IMJCIII M l o i l . t p e d y d r u e j If l f d i u c h o ( Jo i q u l n 10 i nun • Avjilatili (or itrtjming fll

    I 3. In XAML, w rap your main B2 panel into azyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Vi ewbox. You do no t need to set any property on the Vi ewbox, it w ill auto matiFIGURE 4 .1 Scaled Netflix window. cally fill the w ho le space.

    In Expression Blend, right-click the main panel in Objects and Timeline, and select Group Into fro m the co ntext menu. Select a Vi ewbox. This w ill wrap the main panel into the Vi ewbox. Make sure that the Vi ewbox 's Wi dt h and Hei ght are set to Aut o. 4. Test your applicatio n and resize the brow ser w indow . You sho uld see the applica-

    tio n's co ntent being scaled up or dow n to fill the w ho le space.

    Ope ni ng a Chi l dWi ndow

    87

    zyxwvutsrqponml

    W ARN I N G To S ca l e or N ot t o S ca l e

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Choosing to scale or not an application depends a lot on the application's design. You have the following alternatives:

    v



    Scale the application as dem onstrated in this sect ion. This can cause annoying effects, especially if the window is resized to a very sm all size (readability problem ) or very large size (pixilation of im ages). Note that vector im ages, however, will not get pixilated. (SeeyxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB Silverlight 2 Unleashed, Chapter 5, for m ore inform ation about scaling im ages.)



    Change the layout based on the application's size. For exam ple, if you use a grid-based layout, you can let the colum ns be resized dynam ically when the host's size changes (flow layout). Also, you can select different tem plates for your controls based on the control's size, in order, for exam ple, to display fewer details when the application is sm aller. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    As mentio ned , ano ther frequent usage for a Vi ewbox co ntro l is the resizing of Pat h elements, for example w hen they co mpo se a logo. Pat h elements canno t be resized easily, so w rapping them in a Vi ewbox and resizing this bo x instead is a better appro ach.

    Ope n in g a Chi l dWi ndow The Chi l dWi ndow class was actually already present in Silverlight 3. It is a very useful class w hen yo u w ant to present additional info rmatio n in a semi-mo dal w ay to the user. By "semi-mo d al," we mean that the user w ill no t be able to access o ther co ntro ls on the Silverlight application as lo ng as he didn't acknow ledge the dialog; how ever, the applicatio n itself is no t blocked, and co ntinues to process info rmatio n, to run animatio ns, and so fo rth. The dialog is show n in anzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA asynchronous way. To add a Chi l dWi ndow to your Silverlight application, follow these steps: 1. Right-click the pro ject in the So lutio n Explorer, and then select Add, New Item fro m the co ntext menu.

    2. In the Add New Item dialog, select Silverlight Child Windo w ; enter zyxwvutsrqponmlkjihgfedcbaYWVU M yChildW indow as w indow 's name, and click Add. 3. Customize the ChildWindow's lo o k and feel by mo difying its XAML file. Note that yo u can also design the XAML into Expression Blend.

    4. Set the Over l ayBr us h. As show n in Figure 4.2, the Chi l dWi ndow, w hen open, is appearing in fro nt of your Silverlight applicatio n and prevents the user from clicking the co ntro ls below . The Over l ayBr us h is, as the name show s, a brush that can be set as yo u w ant ( Sol i dCol or Br us h, Li near Gr adi ent Br us h, Radi al Gr adi ent Br us h, and so fo rth). For mo re info rmatio n about brushes, refer to Silverlight 2 Unleashed, Chapters 2 and 4.

    88

    CHAPTER 4

    Invest igat ing Exist ing Cont rols

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    W A R N I N G zyxwvutsrqponmlkjihgfedcbaYXWVUTSRQPONMLKJIHGFEDCBA Set t in g t he yxwvutsrponmlkihgfedcbaYWVUTSRPONMLIHGFEDCBA OverlayBrush t o N u l l

    You can set the Overl ayBrush to { x : N u l l } , which m eans that no brush will be applied. Note, however, that all controls on the Silverlight page below the ChildWindow are disabled when it is open. This is, as m entioned previously, a pseudo-m odal dialog. A better idea is to set the Overl ayBrush to a light half-opaque gray (for exam ple, #33999999). zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO

    v



    5. If yo u w ant your user to input info rmatio n, yo u can, for example, save the informatio n in a d epend ency property, as show n in Listing 4.9.

    Ch i l d W i n d o w Sa m p l e zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPO Ch i l d W i n d o w Sa m p l e

    £3

    En t e r t e xt . . .

    You didn't e n t

    6. Note that closing the Chi l dWi ndow is done by setting its Di al ogRes ul t property, as yo u can see in [ OK ] Can ce l Listing 4.9. As so o n as the property is set, the w indow FIGURE 4 .2 Chi l dWi ndow and overlay. is closed automatically. In the default Chi l dWi ndow, the butto n OK sets Di al ogRes ul t to t r ue, and Cancel (as w ell as the X butto n in the title bar) sets Di al ogRes ul t to f al s e.

    ]

    7. To open the Chi l dWi ndow, fro m any page in your applicatio n, instantiate a new MyChi l dWi ndow and call the Show metho d on the new instance, as show n in Listing 4.10. 8. To retrieve the info rmatio n entered by the user after the w indow has been closed,

    yo u can hand le the Cl os ed event as show n in Listing 4.10. Again, this is an asynchro no us pattern, and yo u need to hand le the event to access the w indow 's properties after it has been closed.

    LISTING 4. 9

    1

    The Chi l dWi ndow s Code Behind

    publ i c par t i al cl as s MyChi l dWi ndow : Chi l dWi ndow { publ i c cons t s t r i ng I nput Pr oper t yName = " I nput " ; publ i c s t r i ng I nput { get {

    Ope ni ng a Chi l dWi ndow

    ret urn

    ( s t r i n g ) Ge t Va l u e ( I n p u t P r o p e r t y ) ;

    se t { va l u e);

    }

    p u b l i c s t a t i c r e a d o n l y Depen den cyPropert y

    I n p u t Pr o p e r t y

    = De p e n d e n c yPr o p e r t y.Re g i st e r ( In p u t Prop ert yNa m e, t yp eof (st r i n g), t yp e o f (M yCh i l d W i n d o w ), new Pr o p e r t yM e t a d a t a (" En t e r public

    t ext ..." ));

    MyChildWindow()

    I n i t i a l i ze Co m p o n e n t ( ) ;

    p r i v a t e vo i d OK B u t t o n _Cl i c k (o b j e c t t h i s.Di a l o gResu l t

    se n d e r , Rou t edEven t Args e)

    = t rue;

    p r i v a t e vo i d Ca n c e l B u t t o n _ Cl i c k ( o b j e c t t h i s.Di a l o gResu l t

    L I STI N G 4 . 1 0

    sen d er , Rou t edEven t Args e)

    = f al se;

    Opening t he Window and Handling Its Cl o s e d Event

    p r i v a t e v o i d Op en W i n d o w Bu t t o n _Cl i ck (o b j ect {

    sen d er , Rou t edEven t Args e)

    va r window = new M yCh i l d Wi n d ow (); w i n d ow .Cl osed += w i n dow _Cl osed; w i n d o w .Sh o w ();

    } vo i d w i n d o w _Cl o se d (o b j e ct {

    sen d er , Even t Ar gs e)

    va r window = sender as MyChildWindow; if

    (window != n u l l && w i n d o w .Di a l o g Re su l t

    {

    == t r u e )

    zyxwvutsrqponmlk

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    }

    Se t Va l u e ( I n p u t P r o p e r t y ,

    89

    90

    CH A P TER 4

    I n ve s t i g a t i n g Exi s t i n g Co n t r o l s

    I nput Te xt Bl oc k. Te xt

    = wi n d o w. I n p u t ;

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFE

    }

    Like all the co ntro ls in Silverlight, the Chi l dWi ndow can be styled and templated to change its appearance co mpletely if needed. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB

    Finding M ore Inform a tion Because Silverlight 4 co mes w ith such a large range of controls, it is materially impossible to detail all of them. Thankfully, w hen yo u install the Silverlight tools, yo u get a d o cumentatio n file, to o . You can dow nload this file from http:/ / w w w .galasoft.ch/ sl4-offlinedoc. The d o cumentatio n is also available o nline. The page specific to the built-in co ntro ls' d o cumentatio n is at http:/ / w w w .galasoft.ch/ sl4-onlinedoc.

    W he re to Find Additiona l Cont rols? As so o n as Silverlight 1.0 was released, third-party providers started creating co ntro ls to cover w hat was missing from the core framew ork. As Silverlight became mo re and mo re elaborate and pow erful, many of the co ntro ls were made available to users of the core, and it is possible to create a very rich applicatio n w itho ut resorting to external providers.

    Do You Rea lly Need a Cont rol? An interesting side effect of the templates system in Silverlight is that it is no w possible to change the functio nality of an existing co ntro l in such a w ay that it fulfils your requirement even tho ugh it was no t intend ed for this purpose at first. For instance, the CheckBox and the Radi oBut t on co ntro ls are essentially Toggl eBut t on instances: This special kind of butto n has three states ( Checked, Unchecked, and I ndet er mi nat e) . Turning such a co ntro l into a CheckBox simply requires a different template to change the co ntro l's appearance, as show n in Figure 4.3. The functio nality remains, for the mo st part, unchanged . Note that the default template for Radi oBut t on and for Toggl eBut t on d o n o t d if f erentiate th e Un c h e c k e d an d I nde t e r mi na t e

    states. If yo u w ant a Radi oBut t on that behaves differently, yo u w ill have to mo d ify the template (as yo u w ill see in Chapter 10).

    ^ B U •

    CheckBDX

    |VI CheckBDX

    Rad i cBu t t Dn

    ^ ^ To g g leBurtEn

    ®

    L J CheckBDX

    j l j b L. i L i

    |ToggleButton|

    O

    zyxwvutsrqponmlkjihgfedcbaZ

    FLad i o Bj t t o n

    ToggleBi]fton|

    F I GUR E 4 . 3 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCB Che c k Box ,

    A no ther example is the Li s t Box. This data co ntro l is Radi oBut t on, a n d Toggl e But t on used to represent a list of items. Thanks to the possiin three st at es (in Blend). bility to redesign an item's template (called Da t a Te mpl a t e ) completely, as w ell as the Li s t Box 's template itself, it is a really versatile co ntro l that can be adapted to many uses.

    W h e r e t o Fi n d A d d i t i o n a l Co n t r o l s ?

    91

    zyxwvutsrqponm

    The Silve rlight Toolk it zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA As previously mentio ned in Chapter 1, "Three Years of Silverlight," the Silverlight team w orks in a very agile manner. One of the principles of this softw are d evelo pment metho d ology is to release small incremental versions, and to release them o ften. However, w hen yo u publish a framew ork as rich as Silverlight, there are limits to ho w o ften yo u can release new versions. So me impo rtant firms have large pro jects, and co nverting them to a new version of Silverlight takes time, costs money, and creates frustration. On the o ther hand, having new co ntro ls as so o n as possible is very impo rtant for o ther customers. For this purpose, Micro so ft is releasing new co ntro ls into a "staging area" called the Silverlight To o lkit. This is a CodePlex pro ject (available at http:/ / silverlight.codeplex.com) w here a large number of co ntro ls are made available to the public, including the source code and unit tests. The Toolkit is a pro bably the first place that developers should check w hen they need a new Silverlight co ntro l. An interesting aspect of the Silverlight Toolkit is that it defines four bands for the included co ntro ls: zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA Experimental band, for controls in early development: This band is used • ThexwvutsrqpnmliecbaSPMJEBA

    mo stly to gather feedback. Co ntro ls in the Experimental band sho uld no t be used in pro ductio n applicatio ns. Also, these co ntro ls may disappear from future versions of the Toolkit. • The Preview band, for controls that are ready for basic scenarios (alpha version):

    So me changes may affect the co ntro l's interface, so yo u might have to edit your code if yo u use these co ntro ls. Using co ntro ls fro m the Preview band in pro ductio n applicatio n is risky, but might be okay, for example, if the applicatio n is no t due for release before a certain time. • The Stable band, for controls that are ready for most scenarios (beta version) but might be subject to a few minor changes in the future: Using these co ntro ls

    in a pro ductio n applicatio n should no t be critical, as lo ng as yo u are aware of their beta-like quality. • The M ature band, for controls that are ready for production: These co ntro ls

    might change in future versions (if security requires it, for example).

    TI P M o vi n g Co n t ro l s t o t h e Co r e Fra m e w ork

    When a new Silverlight fram ework is released, Microsoft includes som e of the controls from Silverlight 2 Unleashed may the Toolkit's Mature band into the core fram ework. Readers of yxwvutsrqponmlkjihgfedcbaWUSRPOMKIHEDB rem em ber that som e of the controls we st udied (such as the Calendar, Dat ePick er, Dat aGrid) were in the Toolkit at that tim e, and are now included into the core Silverlight fram ework. For the developer, converting a Silverlight 2 project to Silverlight 3 or 4 allows rem oving som e external dependencies to assem blies and reducing the size of the application downloaded to the Silverlight plug-in.

    v

    /

    92

    CH A P TER 4

    I n v e s t i g a t i n g Ex i s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    Insta lling the Silve rlight Toolk it zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB The Toolkit can be installed w ith an MSI installer, w hich yo u can dow nload fro m the CodePlex site. By default, all the files get installed into C:\Program Files\Microsoft SDKs \ Silverlight \v4.0 \Toolkit \ [DATE] (w here [DATE] is the Toolkit's date; for example, A prlO). On Windo w s x64 machines, "Program Files" is replaced by "Program Files (x86)". Note that the Toolkit is distributed under the MS-PL license, w hich is Micro so ft's open source license. This grants yo u the right to mo d ify the Toolkit's source code (included w hen yo u install it). Using t he Silve rlight Toolk it in Visua l St udio

    After the Toolkit has been installed, yo u sho uld see all the co ntro ls in the Visual Studio to o lbo x. Visual Studio assists yo u w hen adding co ntro ls to the page by referencing the correct DLLs and adding the required XML namespaces, as yo u w ill see w ith the follow ing steps: 1. Create a new Silverlight 4 applicatio n. 2. Open MainPage.xaml in the Visual Studio designer.

    3. Select the co ntro l that yo u w ant to add fro m the To o lbo x and drag it o nto the designer surface. 4. Customize the co ntro l using the Properties panel.

    TI P If You D on ' t S e e t h e Co n t ro l s in t h e To o l b o x

    Som etim es a control m ight be m issing from the Toolbox. To set up what the Toolbox displays, follow t hese st eps: 1. Right-click anywhere on the Toolbox panel. 2. Select Choose Item s from the context m enu. Opening t his dialog can take quite a long tim e. 3. In the Choose Toolbox Item s dialog, select the Silverlight Com ponents t ab. Then check or uncheck the controls you want to display or hide. 4. Click OK. The Toolbox should now be updated. \

    /

    Note that yo u can also add a reference to the correct DLL manually, using the Add Reference co ntext menu in the So lutio n Explorer. In that case, yo u must also add an xmlns statement po inting a prefix to the CLR namespace in w hich the co ntro l is lo cated. For instance, thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Accor di on co ntro l that we detail further in this chapter is included in the assembly System. Windo w s.Co ntro ls.Layo ut.To o lkit, in the namespace System.Windo w s.Co ntro ls. Therefore, the XAML code to add an Accor di on co ntro l to the

    Wh er e t o Find Ad d i t i on a l Co n t r o l s?

    93

    zyxwvutsrqponml

    main grid looks like Listing 4.11. You can find the info rmatio n about the co ntro l's DLL and its namespace in the Toolkit's d o cumentatio n (and thro ugho ut this chapter). LISTING 4 .1 1

    Adding an Accordi on Control in XAML

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED





    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Using the Siive riight Toolk it in Expre ssion Ble nd

    In Blend, using a co ntro l fro m the to o lkit is a quite easy, to o , as the follow ing steps show : 1. Create a new Siiveriight 4 applicatio n in Blend. 2. In the Assets library, select the co ntro l or panel that yo u w ant to add to the scene, and drag it on the designer surface. 3. Blend takes care of adding all the references needed for you.

    Exploring the Cont rols

    Together w ith the Toolkit, a sample brow ser (show n in Figure 4.4) gets installed, allow ing yo u to explore the co ntro ls included, understand ho w they can be used and get sample XAML, C#, and VB.NET code. The Toolkit sample brow ser can be started fro m the Micro so ft Siiveriight 4 Toolkit folder in your Start menu. The full source code is also installed on your machine and a link is available in the Toolkit folder in the Start menu.

    94

    CHAPTER 4

    Invest igat ing Exist ing Cont rols

    B V i e w Fu l l Sc r e e n

    FIGURE 4 .4

    BuLibleSdrnplE.M rnl

    zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKI

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    Q BubbleSdrnplc.A drnl.ui

    Q

    BubbleSdiuple.xdml.vb

    Toolkit sam ple browser with a bubble chart sam ple.

    In the version of the Silverlight Toolkit that is current at the time of this w riting, yo u w ill find the follow ing co ntro ls: yxwvutsrponmlkihgfedcbaYWVUTSRPONMLIHGFEDCBA



    Chart, Rating, NumericUpDown, TimeUpDown, DomainUpDown, GlobalCalendar, TimePicker, Expander, Accordion, LayoutTransformer, TransitioningContentControl, DockPanel, WrapPanel, ContextMenu: These co ntro ls and panels are review ed further in this chapter.



    DescriptionView er, Label, ValidationSummary, DataForm, Busylndicator: These co ntro ls are used in scenarios requiring data entry. You'll learn mo re about these co ntro ls in further chapters.



    A large number of themes: Themes can be applied to your applicatio n w itho ut yo u having to create styles and templates for the co ntro ls. The implicit theme w ill be picked up by all the co ntro ls in your application, unless of course yo u specify otherw ise. You w ill see ho w to apply a theme to your applicatio n in Chapter 10. zyxwvutsrqponmlkjihgfedcbaZY

    Cha rt

    Nam espace: Syst em .Windows.Cont rols.Dat aVisualizat ion.Chart ing Assem bly: System .Windows.Controls.DataVisualization.Toolk it.dll

    Charting is traditio nally an area w here third-party providers have been active and provide, in some cases, advanced so lutio ns. However, for many smaller applications, the cost of such a professional so lutio n can be pro hibitive. This is w hy the Silverlight Toolkit's chart co ntro ls are a very interesting alternative.

    W h e r e t o Fi n d A d d i t i o n a l Co n t r o l s ?

    95

    zyxwvutsrqponml

    At the time of w riting, the follow ing chart types are available in the Toolkit: Area, Bar, Bubble, Co lumns, Line, Pie, Scatter, and Stacked. So me of these chart types are show n in Figure 4.5. The charts available allow a great level of flexibility, including the possibility to define multiple series, custo m axis, and even d ynamic data w ith the chart being animated as the data is changing.

    FIGURE 4. 5

    Three t ypes of chart s: Colum n, Line, Pie.

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    Ra t ing

    Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.lnput.Toolk it.dll

    ThezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Rat i ng co ntro l is interesting w hen yo u w ant to ickicirü yxwvutsrponmlkjihgfedcbaYXWVUTSRQPOM allow your applicatio n's user to rate an article, a picture, and so fo rth. Like mo st of the co ntro ls in the Silverlight Toolkit, this co ntro l can be used w ith a default style or Hate Bo r e d Ease Am u s e d La u gh t er w ith a custo m style/ template, allow ing an unlimited range of changes, as show n in Figure 4.6. Note that the FIGURE 4 .6 Rating control in default style, and with number of items (stars, bullets, and so o n) can be custom ized tem plate. custo mized thro ugh a property; also, the rated value is a double, allow ing for fractio nal values to be entered. Num ericllpDown, Tim eUpDown, DomainUpDown Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.lnput.Toolk it.dll

    These three co ntro ls all derive from the same base class named UpDownBas e. This is a generic co ntro l, and can be extend ed for additional types if needed. These co ntro ls have an input area and a spinner butto ns. The butto ns are used to increment the value, w hile the input area can be used to jump to a value by entering it using the keyboard. Because the Silverlight Toolkit co mes w ith the source code, yo u can check ho w the team created these controls, and inspire yourself from that so lutio n to create your ow n up-dow n co ntro l:



    Numer i cl l pDown is used to "sp in" numeric values. This is the simplest of the three co ntro ls. vtsrnmlkihgedcaVUSRNMKEA

    96

    CHAPTER 4

    In vest i ga t i n g Exi st i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED



    Ti mel l pDown, zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA like the name shows, is used to "sp in" time values. Depending o n the lo catio n of the cursor in the co ntro l's input area, either the hours, the minutes, or (if available) the AM/ PM indicato r are spun. Note that yo u can change the time representatio n by using the Cul t ur e property (for example, en-US or fr-CH).



    Domai nl l pDown is the mo st co mp lex of the three up-dow n co ntro ls available in the Toolkit. In fact, it is mo re of a data co ntro l: You can data bind its I t ems Sour ce property to a co llectio n of items. You can also customize the items' appearance by creating a data template and assigning it to the I t emTempl at e property. Thus, the Domai nl l pDown is quite similar in its usage to a Li s t Box.

    The Silverlight Toolkit's sample brow ser has many examples of up-dow n co ntro ls in the Input sectio n. Make sure to check them o ut and review the source code to understand ho w they are configured. Gl oba l Ca l e nda r Na me s p a c e : Sys t e m. Wi ndows . Cont r ol s As s e mbl y: Sys t em. Wi ndows . Cont r ol s . Tool ki t . dl l

    A co ntro l very similar to the Cal endar co ntro l that is available in the core framew ork, the Gl obal Cal endar can display years, mo nths, and dates for a given culture. To change the culture of the Gl obal Cal endar to ja-JP (Japanese culture), use the code in Listing 4. 12. LI STI NG 4 . 1 2

    Set t i ng t he Gl oba l Ca l e nda r ' s Cul t ur e

    MyCa l e nda r . Ca l e nda r I nf o = ne w Cul t ur e Ca l e nda r I nf o( ne w Cul t ur e I nf o( " j a - J P" ) ) ;

    Ti me Pi c ke r Na me s p a c e : Sys t e m. Wi ndows . Cont r ol s

    6: 45: 00 PM t | ( l

    As s e mbl y: Sys t em. Wi ndows . Cont r ol s . l nput . Tool ki t . dl l

    The Ti mePi cker is co mplementary to the already w ell-know n Dat ePi cker that was available in earlier versions of the Toolkit, and as of Silverlight 3, inside the core Silverlight framew ork. It is co mpo sed of a Ti mel l pDown co ntro l (w hich we discussed earlier in this chapter) and a small butto n shaped as a clock. The clo ck displays a pop-up allow ing selecting a time. Note that the popup can be custo mized to display a range co ntro l w ith sliders, as show n in Figure 4. 7. Also, the Ti mePi cker can be custo mized for a given culture (w ith the Act ual Cul t ur e property) and for a given fo rmat (using the Act ual For mat property). Expander Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.Toolk it.dll

    la 8

    C

    PM

    55

    PM

    5n

    FI P M

    LJ 4

    PM

    2 PM

    45 40

    IZ

    PM

    30

    IA

    AM

    75

    0

    AM

    20

    SAM

    15

    •1 A M

    10

    2

    AM

    1 2 AM

    ZI

    35

    05

    ao

    0 0

    FIGURE 4 .7 zyxwutsrponmlkjihgfedcbaWVUTSRP Ti me Pi c k e r wit h Range Ti me Pi e k e r Popup.

    Wh er e t o Find Ad d i t i on a l Co n t r o l s?

    97

    zyxwvutsrqponm

    Ac c o r d i o n

    Nam espace: Syst em .Wi n dow s.Con t rol s Assem bl y: Syst em .Windows.Cont rols.Layout .Toolk it .dll

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    ThezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Expa nde r and Ac c or di on co ntro ls are tw o co ntro ls used to hid e/ sho w their c o ntent to create flexible layo ut. The Expa nde r has o ne Cont e nt pro p-

    *

    erty that can be any o bject (as is usual fo r Cont e nt Cont r ol s ) . The

    expand to the right

    Cu st o m er 1

    Aa be rg,

    10000000

    Aa be rg,

    Je s p e r

    Je s p e r

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML 10000000

    Cont e nt w ill be exp and ed / co llap sed

    *

    w hen the user clicks the head er, y o u w e see in Figure 4.8:

    Customer 2 Customer 3

    v

    Ada m s,

    Te rry

    10000002



    If the Con t en t is a string, a Te xt Bl o c k w ill be used auto mat-

    FI GURE 4 . 8 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCBA Ex pande r and Ac c or di on cont rol s,

    ically fo r the display. •

    If the Cont e nt is a UI El e me nt , it w ill be rend ered .



    For d ata items, y o u can set the Cont e nt Te mpl a t e p ro p erty to sp ecify ho w the item m ust be rend ered .

    The Ac c or di on co ntro l w o rks a little like the Expander , but w ith multip le Ac c or di onl t e m instances, each w ith a Cont e nt p ro p erty and a He a de r as seen o n Figure 4.8. Yo u can either set the Ac c or di onl t e m instances manually , o r b ind the Ac c or di on 's I t e ms Sour c e p ro p erty to a co llectio n, like w ith o ther d ata co ntro ls. Dep end ing o n the Se l e c t i onMode pro perty, the Ac c or di on m ay d isplay o ne o nly o f the item s (auto matically clo sing the o thers), or just leave them o pen/ clo sed as the user activ ates them . O ther p ro p erties such as Se l e c t i onSe que nc e ( Si mul t a ne ous or

    Col l a ps e Be f or e Expa nd) and Expa ndDi r e c t i on g o v ern the w ay that the Ac c or di onl t e m instances are expand ed / co llapsed , as sho w n in Listing 4.13. L I STI N G 4 . 1 3

    Expander and Accordion Cont rols





    La yout Tr a ns f or me r Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.Layout.Toolk it.dll

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    This co ntro l is quite specialized. WPF developers are familiar w ith the tw o types of transfo rmatio ns that this framew ork offers: Render Tr ans f or m (available in Silverlight) and Layout Tr ans f or m (no t available in Silverlight). The main difference is that Render Tr ans f or m w ill mo d ify the elements after the layout pass is co mpleted. Other co ntro ls are no t affected by a Render Tr ans f or m. This can create unw anted side effects. For example, Figure 4.9 show s three But t ons in a St ackPanel . The middle butto n is transfo rmed by a Render Tr ans f or m (45-degree Rot at eTr ans f or m) .

    FIGURE 4 .9

    zyxwutsrponmlkjihgfedcbaWVUTSRPL

    Re nde r Tr ans f or m applied to a button.

    On the o ther hand, the Layout Tr ans f or m is applied before the layout pass, w hich means that o ther co ntro ls' placement (and in some case their size) w ill be mo dified according to the transfo rmed element (as show n in Figure 4.10). Because Layout Tr ans f or m is no t available in the core Silverlight framew ork, how ever, using the Layout Tr ans f or mer instead solves the issue (see Listing 4.14). You can find mo re info rmatio n about this co ntro l o n its developer's blog, David A nson: http:/ / w w w .galasoft.ch/ sl4-layouttransform.

    FIGURE 4 .1 0

    Lay out Tr ans f or m applied to a button (with

    Lay out Tr ans f or me r ) .

    Where t o Find Addit ional Cont rol s?

    LISTING 4 .1 4

    LayoutTransform Applied to a Button (with LayoutTransform er)

    99

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSR







    Tr a ns i t i oni ngCont e nt Cont r ol Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.Layout.Toolk it.dll

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK

    This co ntro l can be used in place of a standard Cont ent Cont r ol to create a smo o th transitio n betw een tw o different co ntents. The transitio ns are specified using visual states. By default, the co ntro l know s the " UpTr ans i t i on" (the old co ntent shifts up before being replaced by the new co ntent) and the " DownTr ans i t i on" (the exact opposite). You can also specify different transitio ns using the Vi s ual St at eManager . You can find mo re info rmatio n about the Tr ans i t i oni ngCont ent Cont r ol o n Jesse Liberty's blog, at http:/ / w w w .galasoft.ch/ sl4-transitioncontrol.

    Doc kPa ne l Nam espace: Syst em .Windows.Cont rols Assem bly: System .Windows.Controls.Toolk it.dll

    The DockPanel is w ell kno w n fro m WPF. It is useful to lay out your application by ancho ring UI elements to various sides of the panel. To change w hich side of the panel an element is docked to, use the Dock Panel.Dock attached property. Its value can be Lef t , Ri ght , Top, or Bottom , as show n in Listing 4.15. For mo re info rmatio n about attached properties, see Chapter 5, "Und erstand ing Depend ency Properties." In addition,, yo u can specify w hether the last element added to the panel must fill the rest of the space. Depending on the value of the Las t Chi l dFi l l property o n the DockPanel , the layout w ill vary, as show n in Figure 4.11. The default for this property is Tr ue.

    FIGURE 4 .1 1 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCBA Las t Chi l dFi l l property set to

    Fal s e or Tr ue .

    100

    CH A P TER 4

    LI STI NG 4 . 1 5

    I n ve s t i g a t i n g Exi s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFED

    Set t i ng El e me nt s i n a Do c k Pa n e l





    Wr a p Pa n e l Na me s p a c e : Sys t e m. Wi ndows . Cont r ol s As s e mbl y: Sys t em. Wi ndows . Cont r ol s . Tool ki t . dl Wr a p Pa n e l s zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA are useful to d isp lay m u ltip le ite m s in a ro w , w ith th e ab ility to w rap o n th e n e x t

    Aab er g, .

    A d a m s, I

    A d a m s, -

    Bu g n i o n ,

    H i ck s, C i

    A r ge n t i e i

    Pe n o r , Lt

    Pf ei f f er , I

    line w h e n th e p ane l is resiz ed . This ab ility is esp ec ially interesting w h e n th e Wr a p Pa n e l is

    Ph i l i p s, C

    u sed as th e p resenting p ane l fo r a d ata c o ntro l, su c h as a Li s t Box. To d o this, just set th e

    Li s t Box 's I t e ms Pa ne l p ro p erty to a Wr a pPa ne l , as

    F I GURE 4 . 1 2 Us i ng a zyxwutsrponmlkjihgfedcbaWVUTSRPLIGF Wr apPane l a s I t e mPane l f or a Li s t Box . zyxwvutsrqponmlkjihgfedcbaZYXW

    sh o w n in Listing 4. 16 an d in Fig ure 4. 12.

    LI STI NG 4 . 1 6 f or a Li s t Bo x

    Us i ng a Wr a p Pa n e l a s I t e mPa n e l







  • Th e

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Co n t e xt M e n u

    Until rec ently , th e Silv erlig ht d ev elo p er d id n o t h av e an y c o n tro l o n w h at w as d isp lay ed w h e n th e user rig ht- c lic ks o n th e Silv erlig ht ap p lic atio n: T h e Mo u s e Ri g h t Bu t t o n Do wn w as u nav ailab le fo r th e d ev elo p ers, an d reserv ed to d isp lay th e Silv erlig ht m e n u o nly .

    W h e r e t o Fi n d A d d i t i o n a l Co n t r o l s ?

    101

    In Silverlight 4, thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Mous e Ri ght But t onDown event is no w available and can be hand led by your applicatio n, as we w ill see in Chapter 17, "New Transforms, Right Click, HTML Browser, WebBrow serBrush, and Isolated Sto rage." In the Silverlight Toolkit, a Cont ext Menu is even provided. It makes it very easy to build custo mizable co ntext menus, for example w ith the code in Listing 4.17. Note that each menu item can also display ico ns if desired. LISTING 4 .1 7







    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Third-Pa rt y Providers It is hard to keep track of all the third-party providers of Silverlight co ntro ls. It is also very difficult to reco mmend o ne or the other, because it really depends w hat pro blem yo u are trying to solve in your pro ject. The follow ing checklist can be useful w hen trying to cho o se a third party provider for your co ntro ls: • Check the provider's reputatio n o nline. Thankfully, w ith mo dern means of co mmunicatio n such as o nline forums or Twitter, users are mo re vocal than they used to be. It is fairly easy to find info rmatio n o nline abo ut a provider. • However, remember that users are much mo re pro ne to vo ice negative co mments than positive ones. So, take each co mment o nline w ith a grain of salt. If yo u are in doubt abo ut w hat really happened, do no t hesitate to co ntact the person w ho w rote the co mment to ask for clarificatio n. • If yo u d o n't find info rmatio n about the provider yo u are interested in, post your questio ns about them, either on Tw itter or on ind epend ent forums such as http:/ / w w w .silverlight.net. • Check w hat support plan the provider is offering. Will yo u get a guaranteed answ er if yo u have an issue, and in w hat time frame? Many providers offer help thro ugh o nline forums o n their w ebsite. Take some time to check the quality of the replies, and w ho w rote them: Is it a member of the support team? Is it the developer himself (in w hich case, it might mean that there is no dedicated support team)?

    zyxwvutsrqponmlk

    102

    CH A P TER 4

    I n v e s t i g a t i n g Ex i s t i n g Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIH

    • Are the controls free or "cheap"? What does this imply in terms of quality? Although some free controls have a really good quality and might totally fulfill your needs, do no t underestimate the value of a good support team. • What is your relationship w ith this provider? Did you have experience w ith other of their products? Many professional controls providers have offerings in other technologies too (such as ASP.NET, WPF, Windows Forms, and so on). Did someone in your firm work w ith them already? • Is there a possibility to evaluate the controls? If yes, for how much time, and under w hich conditions? • How good is the documentation? Is it easy to find information about the controls' interface? Can you find working samples? In summary, plan enough time to evaluate carefully the different offerings. Remember that controls providers cater to a large audience, and their controls are designed to cover a large spectrum of uses. You are most probably going to have to customize the controls for your specific application. This is going to take some time, and you w ant to take precautions before you start coding. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Sum m a ry Silverlight 4 is the most mature version of the framework. This maturity is clearly visible in the number of controls available, and in the means provided by the framework to build new controls. In this chapter, we talked about various changes in the Silverlight framework to facilitate the creation of controls and their use in Silverlight applications. With these changes, the framework is becoming richer and more compatible w ith Windows Presentation Foundation and more able to support your needs as a developer and a designer. With this maturity, we see the appearance of a large number of controls, w ithin the framework and outside; so much so in fact that every developer intending to use controls in his project should plan enough time to evaluate the various offerings. We talked about the three main sources of Silverlight controls: the Silverlight framework itself, the Silverlight Toolkit, and third-party providers. We also reviewed some of the controls available, and you worked through an application w ith a number of samples. Additional samples for the Silverlight Toolkit are available in the toolkit sample browser that is provided w hen the toolkit itself is installed on a development machine.

    CHA PTER

    5

    Understanding Dependency Properties

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONML I N TH I S CH A P TER , W E W I LL: •

    • See how dependency properties are registered. •

    T h e d epend ency property system is pro bably o ne of the mo st impo rtant fund aments of Silverlight (and Window s Presentatio n Fo undatio n, to o ). A lo t of functio nality is based o n d epend ency o bjects and their properties (mo st impo rtant, data bind ing and the animatio n system).

    Discover the dependency property syste m and the DependencyObject cla ss.

    Talk about a tta ched propertie s, another kind of dependency properties.

    • See how a tta ched properties ca n be used to becom e a tta ched behaviors. •

    Understa nd how a dependency property's value is ca lcula ted. zyxwvutsrqponmlkjihgfedcbaZYXWVUTS

    In fact, many of the types used in the Silverlight framew ork derive from thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA DependencyObj ect class, as the follow ing steps show : 1. Open the Silverlight 4 d o cumentatio n (available offline, CHM file, fro m http:/ / w w w .galasoft.ch/ sl4-offlinedoc, or o nline at http:/ / w w w .galasoft.ch/ sl4-onlinedoc).

    2. Navigate to a class (for example, the Scr ol l Vi ewer co ntro l, in the namespace System. Window s. Co ntro ls). 3. Scroll dow n until yo u see the class hierarchy, as show n in Figure 5.1.

    4. No tice ho w the seco nd highest class in the hierarchy (directly under the Obj ect class) is DependencyObj ect . You are likely to enco unter DependencyObj ect very o ften in Silverlight. For example, all the classes that derive from UI El ement (that is, all the elements that can be drawn on the screen) are also DependencyObj ect instances. This show s ho w deeply the d epend ency property system is ro o ted in the Silverlight framew ork.

    104

    CH A P TER 5

    Un d e r s t a n d i n g D e p e n d e n c y P r o p e r t i e s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    InzyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA Silverlight 2 Unleashed, Chapter 15, we explored B In h e ri tan c e H ierarc hy Sy stem .O b jec t the class hierarchy and explained w hat role the zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Sy stem . Window s. D ep end ency O bject obj e c t , De pe nde nc yObj e c t , UI El e me nt , an d

    Fr amewor kEl ement classes play. It is a good mo ment to refresh your memo ry if needed before we dive deeper.

    Sy stem . Window s. UIElement Sy stem . Window s. Fre mewDrkEI em ent Sy stem . Wi n dDws. Co ntro l 5. Co ntro l S yste m. Wi n do w s. CDntrc 15. Co ntentCa ntra I

    S v s 1 e m. WI r H 1 o v.s. [ a nt ro Is .Si r' > 117 ewer

    zyxwvutsrqpo

    F I GUR E 5 . 1 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCBA Sc r ol l Vi e we r control class hierarchy.

    I nhe rit ing De pe nde nc yObj e c t The DependencyObj ect class serves tw o majo r purposes: • Providing an interface to facilitate interactio n betw een threads • Hosting d epend ency properties

    Thre a ding We w ill talk about threading in mo re detail in Chapter 22 "A dvanced Develo pment Techniques." W hat we need to remember for no w is that mo st o bjects are o w ned by the thread that created them. In mo st cases, this is the main thread of the applicatio n (called the UI thread) that ow ns the o bjects (for instance, all the UI El ement instances). However, w hen lo ng-running tasks are executed on the UI thread, all o ther activities are blo cked until that task is co mpleted. It means that animatio ns w ill no t run anymo re, and the co ntro ls w ill no t react to user input. This is a rather irritating effect that hinders the user experience. In such a case, the best practice is to spawn a backgro und thread (as we w ill do in Chapter 22). This way, the UI thread is no t blo cked and can process animatio ns and user input. However, every access fro m the backgro und thread to the o bjects ow ned by the UI thread (including all the UI El ement instances, as mentio ned previously) must be dispatched to avoid a crash in the applicatio n. The DependencyObj ect has tw o members to help yo u w ith that task: zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPONMLKIHGFEDCBA • The Di s pa t c he r property: Each thread has o ne instance of the Di s pat cher class that

    manages the queue of o peratio ns to be executed on that thread. This is the class yo u use w hen yo u w ant to dispatch an o peratio n from o ne thread to ano ther. Do no t let the fact that the Di s pat cher class and the DependencyObj ect . Di s pat cher property have the same name co nfuse you. • The Che c kAc c e s s method: W hen an o bject calls this metho d on ano ther o bject, the

    metho d returns true if direct access is allow ed. If that is no t the case, the operation must be dispatched. In Chapter 22, we w ill work mo re w ith threading in Silverlight and spend mo re time w ith the Di s pat cher o bject.

    I n h e r i t i n g D e p e n d e n c y Ob j e c t

    105

    zyxwvutsrqponmlk

    Acce ssin g a De pe nde ncy Prope rt y's Va lue zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK Depend ency properties are registered in a static manner, as yo u w ill see in "Registering Depend ency Properties," later in this chapter. It means that the value for each different instance of a class is administrated by the d epend ency property system, and must be accessed using metho d s that are defined o n thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA DependencyObj ect class: • The Se t Va l ue and Ge t Va l ue metho d s are used to set and get the value of a given d epend ency property.

    • The Cl ear Val ue metho d is used to reset the property to its default value. (You w ill see in a mo ment ho w to define a default value for a d epend ency property.) • Tw o metho d s, Re a dLoc a l Va l ue and Ge t Ani ma t i onBa s e Va l ue are used to get the dependency property's value in some special cases, as covered later in this chapter.

    Now that yo u understand better w hat a DependencyObj ect does, let's talk abo ut dependency properties themselves, and ho w to define new ones.

    Using a zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Dep en d en cyOb j e c t a s Da ta Item The DependencyObj ect class itself is abstract in Silverlight and therefo re canno t be instantiated. However, in Silverlight 4, it is possible to derive a class from DependencyObj ect to ho st d epend ency properties. You can then use instances of this class as data o bjects, as show n in Listing 5.1. LI STI NG 5 . 1

    Cu s t o me r Cl a s s I nher i t i ng De p e n d e n c y Ob j e c t

    1

    publ i c c l a s s Cus t ome r

    2 3

    { publ i c c ons t

    5 6 7

    s t r i ng Na me Pr o p e r t y Na me = " Na me " ;

    publ i c s t r i ng Na me {

    8

    9

    : De p e n d e n c y Ob j e c t

    }

    ge t

    { r e t ur n ( s t r i ng) Ge t Va l ue ( Na me Pr ope r t y) ;

    s et

    { Se t Va l u e ( Na me Pr o p e r t y ,

    }

    va l ue ) ; }

    xuomlbQLKHEB

    10 11

    publ i c s t a t i c r e a donl y De p e n d e n c y Pr o p e r t y

    12

    = De p e n d e n c y Pr o p e r t y . Re g i s t e r (

    13

    Na me Pr o p e r t y Na me ,

    14

    t ype of ( s t r i ng) ,

    15

    t y p e o f ( Cu s t o me r ) ,

    16

    ne w Pr o p e r t y Me t a d a t a ( s t r i n g . Emp t y ) ) ;

    17 18

    publ i c Cus t ome r ( s t r i ng na me )

    19

    {

    Na me Pr o p e r t y

    106

    CH A P TER 5

    Un d e r s t a n d i n g D e p e n d e n c y P r o p e r t i e s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    20 xuomlbQLKHEB Na me = na me ; 21

    22

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    }

    }

    See the "Registering Depend ency Properties" sectio n for mo re details about Listing 5.1. zyxwvutsrqponmlkjihgfed Using a Be t t e r Im ple m e nta tion for Da ta Ite m s

    Using full-blow n DependencyObj ect instances to ho st data might no t be the best idea. Using the d epend ency property system requires quite a lo t of code, and if yo u do no t explicitly need it, it is better to avoid creating a DependencyObj ect for this kind of purpose. A better so lutio n is to usezyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA plain old CLR objects (also kno w n as POCO) implementing an interface called I Not i f yPr oper t yChanged. (You met this interface already in Chapter 4, "Investigating Existing Co ntro ls," in Listing 4.6.) This is very co nv enient because data bind ings w ill react w hen the Pr oper t yChanged event that this interface defines is raised. However, raising the event must be d o ne explicitly in code w hen the value of the property changes, w hile d epend ency properties do this automatically. Listing 5.2 show s an alternative imp lementatio n of the Cus t omer o bject, w ith exactly the same features. LI STI NG 5 . 2

    Cu s t o me r Cl a s s wi t h I No t i f y Pr o p e r t y Ch a n g e d

    1

    publ i c c l a s s Cus t ome r

    2

    {

    3 4

    publ i c e ve nt

    :

    I No t i f y Pr o p e r t y Ch a n g e d

    Pr o p e r t y Ch a n g e d Ev e n t Ha n d l e r

    5

    publ i c c ons t

    6

    = " Na me " ;

    s t r i ng Na me Pr o p e r t y Na me

    7 8

    pr i va t e s t r i ng _ n a me = s t r i ng. Empt y;

    9 10

    11 12

    13

    publ i c s t r i ng Na me { ge t { r e t ur n _ n a me ;

    14 15

    } tsromlaL

    16

    17

    s et

    18

    {

    19 20

    if {

    r e t ur n ;

    21

    22

    ( _na me == va l ue )

    }

    23 24

    na me = va l ue ;

    Pr ope r t yCha nge d;

    I n h e r i t i n g D e p e n d e n c y Ob j e c t

    25 26

    107

    Ra i s e Pr o p e r t y Ch a n g e d ( Na me Pr o p e r t y Na me ) ; xuomlbQLKHEB zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA }

    27

    }

    28 29

    publ i c Cus t ome r ( s t r i ng na me ) { {

    30 31

    Na me = na me ;

    32

    }

    33 34

    pr i va t e voi d Ra i s e Pr o p e r t y Ch a n g e d ( s t r i n g { {

    35 36

    if

    37

    {

    ! = nul l )

    Pr ope r t yCha nge d(

    38

    t hi s ,

    39

    ne w Pr o p e r t y Ch a n g e d Ev e n t Ar g s ( p r o p e r t y Na me ) ) ;

    40

    }

    41 }}

    42 43

    ( Pr ope r t yCha nge d

    pr ope r t yNa me )

    }

    • Line 3 implements the I Not i f yPr oper t yChanged interface by declaring the Pr oper t yChanged event. • Line 5 declares the name of the property as a constant. String-based identifiers should be stored in constants to avoid errors w hen the identifier is used in another part of the code. • Line 8 declares an attribute for the Name property value and initializes it. • Lines 12 to 15 are a simple getter for the Name property. • Lines 19 to 22 verify w hether the property is actually changed by the o bject calling it. If it is unchanged, we simply return, to avoid raising the Pr oper t yChanged event unnecessarily. • Line 25 calls a utility metho d declared a little further in the code, w hich raises the Pr oper t yChanged event. • Lines 34 to 42 are declaring this utility metho d: First we check that the Pr oper t yChanged event is no t nul l . In .NET, events are nul l if no other object registered for them. That would be the case if no data binding and no other o bject used the Cus t omer o bject. Raising the Pr oper t yChanged event if it is nul l will crash the application. • Finally, on line 38 to 40, we raise the Pr oper t yChanged event. By co nventio n, the first argument of this event (and all other events in .NET) is the event sender, w hich we set to this. The second argument is an instance of Pr oper t yChangedEvent Ar gs , w hich carries the name of the changed property as payload.

    zyxwvutsrqponmlkjih

    108

    CH A P TER 5

    Un d e r s t a n d i n g D e p e n d e n c y

    Pr op er t i es

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    W ARNI NG Usi n g "M a g i c S t r i n g s"

    Many areas in Silverlight rely on what program m ers in the Silverlight com m unity call "m agic st rings." For exam ple, registering a dependency property requires the nam e of this property to be passed as a string to the DependencyPropert y. Regi st er m ethod. This is dangerous because if you want to m odify the nam e of one of t hese identifiers, you m ust look everywhere in your code (and XAML!) to make sure that you changed it correctly. Using const ant s to store string identifiers (as on line 3) is a good st ep to avoid such errors. Unfortunately, t his is not possible in XAML. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    v

    /

    The imp lementatio ns in Listing 5.1 and Listing 5.2 are equivalent fro m a data bind ing p o int of view. However, Listing 5.2 does no t rely on the d epend ency property system at all. POCO o bjects like this o ne are easier to hand le for o ther o bjects: They can be easily tested (for example, in unit tests), passed to web services, serialized for safekeeping, and so fo rth. This is w hy it is usually better to rely o n implementing I Not i f yPr oper t yChanged for data o bjects, and reserve DependencyObj ect instances for user interface o bjects such as co ntro ls, UI elements, and so fo rth.

    Re giste ring Dependency Prope rtie s As yo u saw in Listing 5.1, a d epend ency property needs to be registered using the static metho d DependencyPr oper t y. Regi s t er . Let's review Listing 5.1 and understand w hat we implemented : • Line 3 stores the name of the property in a co nstant. Like w hen we imp lemented I Not i f yPr oper t yChanged in Listing 5.2, it is a good practice to store any string identifier in a co nstant to avoid errors w hen using this identifier. • Lines 5 to 9 declare a getter and a setter for the Name property. The getter uses the metho d Get Val ue implemented by the DependencyObj ect base class. Similarly, the setter uses the metho d Set Val ue. The value of the property is no t stored locally, but is instead stored w ithin the d epend ency property system.

    W ARNI NG Co n ve n i e n ce Ge t t e r a nd S e t t e r

    In fact, the property getter and set t er declared on lines 5 to 9 of Listing 5.1 are not used by the data binding syst em or the anim ation syst em to m odify the property's value. They are only here for convenience: It is easier to use the Name property directly instead of having to call the m ethods Get Value and Set Value each tim e. \

    /

    Re gi st e r i n g D e p e n d e n c y Pr o p e r t i e s

    109

    zyxwvutsrqponmlk

    • Lines 11 to 16 are w here the actual registration takes place. The static metho d zyxwvutsrqponmlkjihgfedcbaZYX DependencyPr oper t y. Regi s t er takes four parameters: The name of the property that is registered. We use the co nstant we declared on line 3 The type of the d epend ency property The type of the o bject to w hich the d epend ency property belo ngs An instance of the Pr oper t yMet adat a class, w hich we discuss in the "Defining Metad ata" section, next. • Note that the o bject returned by the Re gi s t e r metho d is saved, and used as an identifier for the d epend ency property. It is used in various o ccasio ns (for example, w hen a bind ing is created in code, as yo u w ill see in Chapter 6, "Working w ith Data: Binding, Grouping, Sorting, and Filtering." • Finally, we declare a co nstructo r for the Cus t omer class. No tice ho w we use the co nv enience setter for the Name property on line 20. Because the co nv enience getter and setter are public, o ther o bjects can use them to set and get the d epend ency property's value. Of course, depending o n your implementatio n, yo u might w ant to restrict the getter's or the setter's visibility. You can even delete the Name getter and setter alto gether and rely o nly on the metho d s Get Val ue and Set Val ue if yo u prefer. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Defining M e t a da t a The d epend ency property system requires a little mo re info rmatio n during the registratio n process. We provide this info rmatio n using an instance of the Pr oper t yMet adat a class.

    TI P W hy M eta da ta ?

    The DependencyPropert y. Regi st er m ethod was im plem ented first in Windows Presentation Foundation (WPF, Silverlight's richer counterpart for the Windows desk top). In fact, the Regi st er m ethod and the m etadata syst em available in WPF are m ore com plex than the ones in Silverlight, and allow for m ore functionality. The syntax available in Silverlight m ight seem a little cum bersom e at tim es, but it is in fact there for reason of com patibility with the richer WPF fram ework. \

    zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA

    Se t t ing a De fa ult Va lue

    The Pr oper t yMet adat a co nstructo r allows setting a default value for the property. Every time that an instance of the Cus t omer o bject is created, the Name d epend ency property is set to s t r i ng. Empt y.

    /

    110

    CH A P TER 5

    Un d e r s t a n d i n g D e p e n d e n c y P r o p e r t i e s

    Ha ndling a Prope rt y Cha nge

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    As mentio ned earlier, the data bind ing system as w ell as the animatio n system set a property's value thro ugh the base class'szyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Set Val ue metho d , and no t thro ugh the co nv enience setter. Because of this, the o bject yo u are implementing w ill no t be no tified if ano ther o bject sets o ne of its properties. To solve this pro blem, yo u need to use a different overload of the Pr oper t yMet adat a co nstructo r and provide a Pr oper t yChangedCal l back delegate. To illustrate this, let's add a d epend ency property named Number Of Changes to the Cus t omer class. This property sho uld be incremented every time that the Name property is mo dified. The registration for the Name d epend ency property beco mes Listing 5.3. LI STI NG 5 . 3 1

    Modi f i e d Na me De p e n d e n c y Pr oper t y wi t h Pr o p e r t y Ch a n g e d Ca l l b a c k

    publ i c s t a t i c r e a donl y De p e n d e n c y Pr o p e r t y

    2 3

    Na me Pr o p e r t y Na me ,

    4

    t ype of ( s t r i ng) ,

    5

    t y p e o f ( Cu s t o me r ) ,

    6

    ne w Pr o p e r t y Me t a d a t a ( s t r i n g . Emp t y ,

    8

    pr i va t e s t a t i c voi d Up d a t e Nu mb e r Of Ch a n g e s (

    9

    De p e n d e n c y Ob j e c t

    10 11

    Up d a t e Nu mb e r Of Ch a n g e s ) ) ;

    d,

    De p e n d e n c y Pr o p e r t y Ch a n g e d Ev e n t Ar g s

    e)

    xuomlbQLKHEB

    {

    12

    va r s e nde r = d a s Cus t ome r ;

    13 14

    Na me Pr o p e r t y

    = De p e n d e n c y Pr o p e r t y . Re g i s t e r (

    s e n d e r . Nu mb e r Of Ch a n g e s ++; }

    • On line 6, no tice that a different overload of the Pr oper t yMet adat a co nstructo r is used: We provide a Pr oper t yChangedCal l back delegate. • The delegate is implemented on lines 8 to 14. Such a delegate has tw o parameters: The DependencyObj ect instance that ow ns the property. This is needed because the delegate is static (like the rest of the d epend ency property system). We use the first parameter to set no nstatic properties or call no nstatic metho d s o n the instance. An instance of DependencyPr oper t yChangedEvent Ar gs . This class co ntains info rmatio n abo ut the property change: The Ol dVal ue, the NewVal ue, and the DependencyPr oper t y o bject that changed. Note that Ol dVal ue and NewVal ue are of type obj ect , and must be cast to the actual type of the property. • On line 12, we cast the first parameter to a Cus t omer o bject. It is no t necessary to check w hether the parameter is actually of this type; it is always the case. • On line 13, we update the property Numbe r Of Cha nge s on the Cus t omer instance. Note that this property is no t present on Listing 5.3 to keep things simpler. You can, how ever, dow nload a w orking sample fro m http:/ / w w w .galasoft.ch/ sl4-inheritdo.

    Re gi st e r i n g D e p e n d e n c y Pr o p e r t i e s

    111

    TI P Ca st i n g a n El e m e n t Usi n g t h e as Ke yw o rd

    The as keyword is used to cast an elem ent from a type to another type (for exam ple, from DependencyObject to Custom er). However, the cast is only successf ul if the original type (DependencyObject) is a super class of the destination type (Custom er). Should that not be the case, the as keyword returns n u l l , but does not throw an exception. This provides a convenient way to make sure that an instance is of a given type without having to t ry/ cat ch an exception. Note that the as keyword cannot be used on value t ypes (such as i n t , double, and so forth) or on s t r u c t t ypes. For t hese t ypes, the casting operator () m ust be used. \

    /

    Because the UpdateNum berOfChanges metho d is defined w ithin the Custom er o bject, it is possible to call private metho d s and to set/ get private attributes and properties on the Propert yChangedCallback delegate's first parameter, because it is also of type Custom er. This can be a little co nfusing at first. There are alto gether three overloads to co nstruct a Propert yMet adat a instance in Silverlight 4. We saw the first o ne in Listing 5.1 and the seco nd in Listing 5.3. The third overload accepts o nly the Propert yChangedCallback delegate, but no default value for the property. In that case, the property's type's default value w ill be used (for example, f a l s e for bool, 0 for i n t , n u l l for o b j e ct , and so fo rth.)

    Initia lizing De pe nde ncy Obje ct s Because of the specificities of d epend ency properties, and because of the fact that o ften DependencyObject is used in XAML do cuments, some precautio ns must be taken w hen initializing them. Choosing a Good Defa ult Va lue

    The default value for the d epend ency property must be cho sen w isely: The Propert yChangedCallback delegate is o nly executed if the property's new value is different fro m the previous value. If your imp lementatio n of the delegate co ntains code that is critical for your o bject's initializatio n, yo u must make sure that it is executed. One w ay to guarantee that this code w ill be executed is to cho o se a default value that the user w ill no t use. It might also be a go o d idea to no tify the user about this, to avoid unw anted side effects. An example is show n in Listing 5.10: The I n i t i a l A n g l e property can be set from 0 to 360 degrees. To guarantee that the Propert yChangedCallback is executed, the default value for this property is set to 400 degrees. Defining a Defa ult Con st ruct or

    You saw in Chapter 3, "Extend ing Your A pplication w ith Co ntro ls," that XAML (like all XML-based languages) requires that the o bjects it ho sts implement a default co nstructo r (that is, a co nstructo r w itho ut any parameters). Because mo st d epend ency o bjects w ill be used in XAML (as UI elements, or as data o bjects), it is good practice to always define an empty co nstructo r and rely on the properties for the d epend ency o bject's initializatio n.

    zyxwvutsrqponmlk

    112

    CHAPTER 5

    Underst anding Dependency Propert ies

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    Remember that in .NET yo u do no t need W ARN I NG to explicitly define a default co nstructo r if there is no o ther co nstructo r in the Un d e r st a n d i n g t h e Si l ve rl i gh t Error class. If yo u define o ne or mo re When you attem pt to create an object in co nstructo rs w ith parameters, how ever, XAML that does not have an em pty construcyo u must explicitly implement a default tor, an error m essage is displayed (see co nstructo r (even if it does no thing) for Figure 5 .2 ). your d epend ency o bject to avoid exceptio ns in XAML. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Tn i t i al i 7 p f i W Bp o n p n t ( ) • 1. Xam lPar seExcep t t o n o ccu r r ed

    x

    No m at ching const ruct or f o u n d o n t ype 'Silver1iqht App1icat ion3,M yClass'. [ U n e 11 Posit ion: 30] 1 r o u b lcsh o o t in g t ips: IGr t q cn M at h r i p f o r t h k e i ce p t » o n .J

    >

    zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA

    Innerf xcept iom If a m et h o d in a class library has been rem oved, recom pile any assem blies t hat reference t hat library, | Get general help for t he inner except ion.

    _

    Search f or m or e H d p Online...

    View Det ail,.. Enable edit inq t npy r i r ep l i n n dr t ail t a I h r r liphoiir d

    FIGURE 5 .2 Error m essage for an object in XAML without em pty const ruct or (shown in Visual Studio). zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    P rot e ct ing t he Code W he n Prope rt ie s Are Se t

    Similarly, remember that o bjects that are used in XAML can have their properties set in any order. YourzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Pr oper t yChangedCal l back code must take this into acco unt. Listing 5.4 show s a DependencyObj ect that we w ill initialize in XAML. This o bject has tw o depend ency properties, Tes t l and Tes t 2. W hen o ne of these properties change, an attribute named _l ower Cas eSt r i ngs is co mputed, by co ncatenating bo th d epend ency properties in low ercase fo rmat. LISTING 5 .4

    Initializing a DependencyObj ect

    1

    publ i c cl as s Dat aObj ect

    2

    {

    : DependencyObj ect

    3

    pr i vat e s t r i ng _l ower Cas eSt r i ngs = s t r i ng. Empt y;

    5

    publ i c cons t s t r i ng Tes t l Pr oper t yName = " Tes t l " ;

    7

    publ i c s t r i ng Tes t l

    8 9 10

    { get { r et ur n ( s t r i ng) Get Val ue( Tes t l Pr oper t y) ; } s et { Set Val ue( Tes t 1Pr oper t y, val ue) ; } xuomlbQLKHEB

    11

    }

    13

    publ i c s t at i c r eadonl y DependencyPr oper t y Tes t l Pr oper t y

    Re g i s t e r i n g D e p e n d e n c y P r o p e r t i e s

    14

    = De p e n d e n c y Pr o p e r t y . Re g i s t e r (

    15

    Te s t l Pr o p e r t y Na me ,

    16

    t ype of ( s t r i ng) ,

    17

    t y p e o f ( Da t a Ob j e c t ) ,

    18

    ne w Pr o p e r t y Me t a d a t a ( n u l l ,

    20

    publ i c c ons t

    22

    publ i c s t r i ng Te s t 2

    23

    {

    s t r i ng Te s t 2 Pr o p e r t y Na me = " Te s t 2" ;

    ge t

    { r e t ur n ( s t r i ng) Ge t Va l ue ( Te s t 2Pr ope r t y) ;

    25

    s et

    { Se t Va l u e ( Te s t 2 Pr o p e r t y ,

    va l ue ) ; }

    }

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJ

    26

    }

    28

    publ i c s t a t i c r e a donl y De p e n d e n c y Pr o p e r t y Te s t 2 Pr o p e r t y

    29

    = De p e n d e n c y Pr o p e r t y . Re g i s t e r (

    30

    Te s t 2 Pr o p e r t y Na me ,

    31

    t ype of ( s t r i ng) ,

    32

    t y p e o f ( Da t a Ob j e c t ) ,

    33

    ne w Pr o p e r t y Me t a d a t a ( n u l l ,

    Up d a t e Lo we r Ca s e ) ) ;

    pr i va t e s t a t i c voi d Up d a t e Lo we r Ca s e (

    36

    De p e n d e n c y Ob j e c t

    37

    De p e n d e n c y Pr o p e r t y Ch a n g e d Ev e n t Ar g s

    38

    d, e)

    {

    39

    va r s e nde r = d a s Da t a Obj e c t ;

    41

    if

    42

    ( s e nde r . Te s t l

    == nul l

    \\ s e nde r . Te s t 2 == nul l )

    43

    {

    44

    r e t ur n;

    45

    }

    47

    s e n d e r . _ l o we r Ca s e St r i n g s

    48

    = s e nde r . Te s t l . ToLowe r ( )

    49

    + s e n d e r . Te s t 2 . To Lo we r ( ) ;

    50

    }

    51

    } •

    zyxwvutsrqponmlkjih

    Up d a t e Lo we r Ca s e ) ) ;

    24

    35

    113

    Bo th Te s t l an d Te s t 2 use th e m e th o d Up d a t e Lo we r Ca s e as their

    Pr o p e r t y Ch a n g e d Ca l l b a c k d eleg ate.

    • This metho d (defined on lines 35 to 50) uses the value of bo th properties to build th e lo w erc ase attrib u te. Lines 47 to 49 w ill th ro w a Nul l Re f e r e nc e Exc e pt i on if either o n e o f th e p ro p erties is nul l .

    114

    CH A P TER 5

    Un d e r s t a n d i n g D e p e n d e n c y P r o p e r t i e s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM

    • To avoid the exception, we protect the metho d w ith lines 41 to 45 and simply exit if the properties are no t set yet.

    • Note that we didn't define any constructor for thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF Dat aObj ect class, w hich means that the default constructor is implicit. This allows us to create a Dat aObj ect instance in XAML (in the resources) w ithout worrying about the order of the properties, as shown in Listing 5.5. LI STI NG 5 . 5

    Cr eat i ng Two Da t a Ob j e c t I ns t a nc e s i n XAML

    If ! Gets or sets the value of the

    2010- - > El e me n t Na me =Ro o t Co n t r o l , Pa t h=MyDa t e Ti me , St r i n g Fo r ma t =D} "

    />

    />

    Di vi ng int o Dat a Bi n d i n gs

    Adding Som e Te xt

    141

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    As shown in Listing 6.9, the formatted parameter can be placed w ithin a string. However, be careful because such text embedded in XAML is impossible to localize. If localization is need ed , yo u need to set thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA St r i ngFor ma t in co d e.

    To embed the formatting information w ithin a text, you need to add an index and enclose everything in curly brackets. However, in XAML, you need to escape the curly brackets to avoid confusing the XAML parser, because you are already in a Bi ndi ng markup extension. The St r i ngFor mat property for a percentage becomes \{0: P2\} in a string. Loca lizin g t h e St r i ngFor ma t Even if the applicatio n's Cur r e nt Cul t ur e and Cur r e nt UI Cul t ur e are set to a culture o ther

    than en-US, this will not be applied to the St r i ngFor mat . This annoying fact can be w o rked aro und by setting the Language pro perty o n the Us e r Cont r ol in w hich the

    binding is applied. The Language property can be applied in XAML or in code, as shown in Listing 6.10. LI STI NG 6 . 1 0

    Set t i ng t he Us e r Cont r ol ' s La ngua ge



    / / I n c ode La ngua ge = Xml La ngua ge . Ge t La ngua ge ( " i t - I T" ) ;

    TI P Using Visua l St udio t o Form a t Binding St rings

    The Vi s ual St udi o Si l ver l i ght des i gner c a n hel p you t o cr eat e a st r i ng f or mat t ed l i ke you want . In t he " Us i ng t he Vi s ual St udi o Bi ndi ng Di al og" s ect i on, l at er i n t hi s chapt er , you will s e e h o w t o s et a bi ndi ng a nd f or mat it us i ng t hi s conveni ent t ool . \

    Ha ndling Spe cia l Ca se s In some cases, the binding does not return a valid value. For example, the source property's name might be misspelled, in w hich case the application does not crash, but the bound value will be left blank. In other cases, the binding is valid, but the value returned is nul l .

    /

    zyxwvutsrqponmlk

    142

    CH A P TER 6

    W o r k i n g w i t h D a t a : B i n d i n g , Gr o u p i n g , So r t i n g , a n d Fi l t e r i n g

    zyxwvutsrqponmlkjihgfedcbaZY

    In SilverlightzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA 4, the Bi ndi ng class has tw o properties taking care of these special cases:



    Tar get Nul l Val ue is used in case the value returned by the bind ing expression is nul l .



    Fal l backVal ue is used in case the bind ing is invalid.

    Note that Tar get Nul l Val ue is used o nly if the value of the bind ing is actually nul l . If the Pat h is co mplex, and o ne of the elements w ithin the path (except the last o ne) is nul l , this is actually an invalid value, and Fal l backVal ue is used instead. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQ

    Prope rty Trigge r In TwoWay bindings, by default, the value of the source property is updated as so o n as the target of the bind ing changes. In some cases, how ever, yo u might need to perform additio nal o peratio ns before no tifying the source that it is changed, for instance if yo u need to perform multiple validatio n o peratio ns before yo u can co nfirm that the value is valid. This can be d o ne by setting the Updat eSour ceTr i gger property to Expl i ci t . In that case, yo u must trigger the update in code w ith the help of the Bi ndi ngExpr es s i on helper class, as show n below . This property is applicable o nly in TwoWay bindings, w here the flow of data does no t o nly go from the source to the target but also in the opposite directio n. Bi n d i n g Ex p r e s s i o n =

    e xpr e s s i on

    My Te x t Bo x . Ge t Bi n d i n g Ex p r e s s i o n ( Te x t Bo x . Te x t Pr o p e r t y ) ;

    e x p r e s s i o n . Up d a t e So u r c e ( ) ;

    Va lida ting Input Validation is used to verify that data is correct according to a set of rules. In Silverlight 2 and 3, the validation mechanism was basic and no t very satisfying. In Silverlight 4, tw o new ways to hand le validatio n errors were added, as yo u w ill see here. In this sectio n, we talk about the way that bind ings hand le validatio n errors. In Chapter 8, "Using Data Co ntro ls," we talk mo re about validation in relation to data co ntro ls. No t i f y On Va l i d a t i o n Er r o r

    This property must be set to Tr ue on the Bi ndi ng expression to trigger the validatio n mechanism. This property was already fo und in Silverlight 2 and 3. Listing 6.12 show s an example using this property. After Not i f yOnVal i dat i onEr r or has been set to Tr ue, the developer of data o bjects can cho o se betw een three different ways to hand le validatio n errors. U s i n g E x c e p t i o n s w i t h Va l i d a t e s On Ex c e p t i o n s

    In Silverlight 2 and 3, the o nly w ay to no tify a bind ing that data is invalid was to thro w an exceptio n. This is still available in Silverlight 4, so existing code w ill co ntinue to w ork. Exceptio n-based validatio n is also useful for the so-called DataA nno tatio ns, w hich are covered in Chapter 8.

    Di vi ng int o Dat a Bi n d i n gs

    143

    zyxwvutsrqponmlk

    Listing 6.11 show s a view -model's property thro w ing an exceptio n w hen the value entered by the user is eitherzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA nul l or empty. Because this property is raising the I Not i f yPr oper t yChanged interface's Pr oper t yChanged event, we can set a bind ing o n this property in TwoWay mo d e. LISTING 6 .1 1

    1 2 3 4

    5 6

    View-m odel's Property Throwing an Exception

    publ i c c ons t s t r i ng Na me Pr ope r t yNa me = " Name" ; pr i va t e s t r i ng _na me = s t r i ng. Empt y; publ i c s t r i ng Na me

    { ge t { r e t ur n _na me ; }

    8

    s et

    9 10

    { if

    11

    {

    12 13

    }

    15

    if

    16

    {

    ( _name == va l ue )

    xuomlbQLKHEB

    r e t ur n;

    17

    ( s t r i ng. I s Nul l Or Empt y( va l ue ) ) t hr ow ne w Exc e pt i on( " Na me s houl d not be e mpt y" ) ;

    18

    }

    20

    _na me = va l ue ;

    tsromlaL

    21

    22 23 24 25 26 27 28

    if {

    ( Pr ope r t yCha nge d ! = nul l ) Pr ope r t yCha nge d( t hi s , new Pr ope r t yCha nge dEve nt Ar gs ( Na me Pr ope r t yNa me ) ) ;

    }

    } }

    Listing 6.12 show s ho w a Text Box co ntro l is bo und to the Name property. W hen the user starts the application, the Text Box is empty and ready for input. If the user enters a name in the bo x, everything is fine. However, if the user then deletes the co ntent of the Text Box, the exceptio n w ill be thro w n in the Name property's setter. This causes the Text Box co ntro l to react by displaying a red border w ith a small red corner, as show n in Figure 6.1. W hen the mo use is over the red corner, the exceptio n's message is displayed in a ToolTip. Every Silverlight co ntro l that allow s input is templated to display the error message w hen the state is invalid. You w ill learn mo re FIGURE 6 .1 Text Box in i nval i d st at e, about this in Chapter 8.

    144

    CHAPTER 6

    LISTING 6 .1 2

    Work i n g w i t h Da t a : Bi n d i n g, Gr o u p i n g, So r t i n g, a n d Fi l t eri ng

    Binding a Text Box with Validation

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGF

    Working w ith exceptio ns for validatio n is simple, but is no t follow ing best practices. Exceptio ns should be reserved for exceptio nal cases, no t just w hen a user makes a mistake w hen entering info rmatio n. Also, the property on w hich the bind ing is applied is responsible for thro w ing the exceptio n, w hich co mplicates the imp lementatio n of such proper-zyxwvutsrqponmlkjihgfed

    I m p le m e n t in g I Da t a Er r or l nf o A cleaner w ay to hand le validation is to let the data o bjects implement the I Dat aEr r or l nf o interface that was intro d uced in Silverlight 4. This interface already exists in the full .NET framew ork for quite some time, and developers are used to this w ay of hand ling validatio n. Also, existing code using this interface can no w be used in Silverlight.

    This interface defines tw o members, but o nly o ne is used in Silverlight. The Er r or property is o nly here for co mpatibility w ith WPF; in Silverlight, we perform o nly propertybased validatio n, w ith the help of the member t hi s j s t r i ng col umnName] defined by I Da t a Er r or l nf o. Listing 6. 13 show s an imp lementatio n of the members defined by I Dat aEr r or l nf o w ithin the view mo del. No tice ho w the validatio n rules are neatly grouped w ithin the t hi s j ] operator, instead of being mixed w ithin the properties. For this to work, the bind ing po inting to the Name property must have its Not i f yOnVal i dat i onEr r or and Val i dat es OnDat aEr r or s properties set to Tr ue, w hile the Val i dat es OnExcept i ons property may be removed. W ith this implementatio n, the Name property defined in Listing 6. 11 remains the same, except for lines 15 to 18, w hich are removed. LISTING 6 .1 3

    IDataErrorlnfo Mem bers in the Viewm odel

    publ i c s t r i ng t hi s j s t r i ng c ol umnNa me ] { ge t { if {

    ( c ol umnNa me == Na me Pr ope r t yNa me ) if {

    ( s t r i ng. I s Nul l Or Empt y( _na me ) ) r e t ur n " Name s houl d not be e mpt y" ;

    }

    Di vi n g i n t o Da t a Bi n d i n gs

    145

    zyxwvutsrqponmlkjihgf

    } zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA r e t ur n nul l ;

    }

    publ i c s t r i ng Er r or { ge t

    { r e t ur n nul l ; }

    } As mentio ned before, the Er r or property is no t used, and always returns nul l . One difference betw een I Dat aEr r or l nf o and the exceptio n-based validatio n we saw in the previous sectio n is that the bindings w ill trigger the validatio n w hen the application starts. On the o ther hand, the exceptio ns are no t queried by the bind ings (that w o uld n't w ork), but thro w n by the property setters, w hich makes it much harder to set the Silverlight application in a validated state w hen it starts. This is yet ano ther argument in favor of the I Da t a Er r or l nf o -based validatio n: Your user w ill know fro m the start w hich fields are compulsory. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Im ple m e nt ing

    I No t i f y Da t a Er r o r l n f o

    The I Not i f yDat aEr r or l nf o interface was also intro duced in Silverlight 4. It provides an additional w ay to hand le validation for mo re co mp lex scenarios than I Dat aEr r or l nf o allow s. Note that this interface is specific to Silverlight for the mo ment, and does no t exist in the full .NET framew ork.

    I Not i f yDat aEr r or l nf o defines three members: •

    Has Er r or s is a bool property that sho uld return t r ue if the o bject has at least o ne error.



    Get Er r or s is a metho d returning a co llectio n (of type I Enumer abl e) . All the errors for a given property name sho uld be placed in that co llectio n and returned to the calling o bject.



    Er r or s Changed is an event that should be raised w hen new errors are detected on o ne property.

    The Er r or Changed event takes an instance of Dat aEr r or s ChangedEvent Ar gs . This class carries the name of the property for w hich the errors co llectio n changed. The main advantage of I Not i f yDat aEr r or l nf o over I Dat aEr r or l nf o is the asynchro nicity: The developer cho o ses w hen the co nsumer (in our case, the bind ing expression) sho uld be no tified that there are o ne or mo re errors. This makes co mp lex validatio n scenarios easier to hand le. Also, errors must no t be strings anymo re; they can be any o bject, in fact. This again enables mo re co mp lex validatio n and no tificatio n scenarios than I Da t a Er r or l nf o.

    146

    CH A P TER 6

    W o r k i n g w i t h D a t a : B i n d i n g , Gr o u p i n g , So r t i n g , a n d Fi l t e r i n g

    Each property in an o bject can have multiple errors. For example, a requirement for the Name property could be to be longer than four characters and include at least o ne space.

    zyxwvutsrqponmlkjihgfedcbaZY

    TI P R e t u rn i n g Ob j e c t s a s Errors

    Should you choose to returns objects rather than st rings when the Get Er r o r s m ethod is called, the objects in question should override the ToSt r i n g () m ethod and use it to return the error m essage that the user interface will display, zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLK v /

    For mo re info rmatio n about I No t i f yDa t a Er r o r l n f o , the Silverlight.net site has a go o d w hitepaper and a sample applicatio n that yo u can dow nload to understand better w hat this interface does. The w hitepaper is available at http:/ / www.galasoft.ch/ sl4-indei. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSR W hich Approa ch Is t he Be st ?

    Using exceptio n-based validatio n is no t reco mmend ed , for the reasons previously listed. Silverlight 4 still supports it for backw ard-co mpatibility reasons, but cho o sing o ne of the tw o validatio n interfaces is the better cho ice. I Da t a Er r o r l n f o is fairly simple to use, but has limitatio ns, as mentio ned earlier (notably, the fact that each property may have o nly o ne error at a time, and that validatio n must be synchro no us can be an issue for co mp lex validatio n scenarios). However, this interface is w ell kno w n, is already used in o ther framew orks (such as Windo w s Forms, WPF, ASP.NET, and so on), and is quite easy to imp lement.

    On the o ther hand, using I No t i f yDa t a Er r o r l n f o in your Silverlight applicatio ns is probably a good idea for mo re co mplex scenarios. This interface is very scalable and suitable for larger applications. It is, how ever, mo re co mplicated to implement.

    Using the Visua l Studio Binding Dia log We talked about the Visual Studio Properties editor in Chapter 2, "Setting Up and Discovering Your Env iro nment." There is, how ever, o ne mo re aspect of this great helper that was no t mentio ned . It can be illustrated by follow ing the steps: 1. Create a new Silverlight 4 applicatio n in Visual Studio. 2. Open MainPage.xaml in the Visual Studio designer. 3. From the To o lbo x, add a Text Box and a Sl i d e r to the main Gr i d and arrange them

    o n the surface. 4. Select the Sl i d e r co ntro l, and in the Properties editor, enter the name M ySl i der for

    it. (Reminder: The name can be entered by passing the mo use over the to p of the Properties editor, next to the Slider label.) 5. Select the Text Box and lo cate the Text property in the Properties editor.

    Next to the property's name, yo u w ill no tice a small ico n. This is a visualization of the origin of the property's value, and can take the shapes and colors illustrated in Figure 6.2.

    Us i n g t h e Vi s u a l St u d i o B i n d i n g D i a l o g

    147



    InheritedzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA means that the value is set somew here "= • + Ç • i ' on o ne of this element's ancestors (for example, FIGURE 6 .2 Property origin: the panel in w hich this element is placed, or the Inherited, Default, Local, panel's parent, and so o n).



    D efault means that this property is no t set and

    Resource, Style, Binding.

    zyxwvutsrqponm

    zyxwvutsrqponmlkjihgfedcbaZY

    takes the default value defined in the element's imp lementatio n. •

    Local means that the property is set on this property explicitly (for example,

    zyxwvutsrqponmlkjihgfedcbaZYX

    Wi dt h=" 100" ) .



    Resource means that this property is set thro ugh a St at i cRes our ce extensio n. You w ill learn in Chapter 10 ho w to create and set resources.



    Style means that the property is set thro ugh a style applied to the element.



    Binding means that this property is set thro ugh a data bind ing.

    W ith the Text Box selected, open the data bind ing editor w ith the follow ing steps: 1. Click the ico n indicating the property's origin and select Apply Data Binding from the co ntext menu.

    2. In the Source section of the editor show n in Figure 6.3, select ElementName, and then the MySlider element. 3. In the Path section of the editor, select the Value property of the Slider.

    4. If yo u need, use the next section, Converter, to select a value converter for the bind ing. We do no t need o ne in this example. 5. Expand the Optio ns sectio n. Here yo u can set the string fo rmat in a friendly way, as w ell as the o ther o ptio ns that we have discussed in this chapter.

    So u r ce

    [ Elem ent Nam e M ySlr der )

    : Path:

    zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPON

    [ Val u e )

    ; Convert er:

    A Op t i o n s

    [TvuoW ay Validat esOnNot îfyDat aErrors )

    St ring Fo r m at

    Ö • H [V]

    M ode: [ Tw o W ay

    -J

    lip dat eSo u r ceTr igg en | Default

    FIGURE 6 .3 Studio.

    Not ifyOnVaIrdat ronError Valïdat esOn Data Errors Validat esOn Except ions Valrdat esOnNot ifyDat aErrors

    IT] Include Ta rget NullValue H

    BindsDir ect lyToSour ce

    m

    Data binding editor in Visual

    6. Set the String fo rmat to {0:N2}, w hich is a numeric fo rmat w ith tw o decimal digits.

    7. Make sure that the Mode is set to Two Way. 8. Run the applicatio n and mo ve the Slider's thumb. Check that the value is updated

    in the Text Box, in the correct fo rmat.

    9. Then, enter a value betw een 0 and 10 in the Text Box, and check that the Sl i der 's value is updated accordingly.

    148

    CH A P TER 6

    W o r k i n g w i t h D a t a : B i n d i n g , Gr o u p i n g , So r t i n g , a n d Fi l t e r i n g

    Using the Expre ssion Blend Binding Dia log

    zyxwvutsrqponmlkjihgfedcbaZ

    zyxwvutsrqponmlkjihgfedcbaZYXWV

    Expression Blend offers a similar functio nality. To o pen the bind ing editor in Blend, follow these steps: 1. In Expression Blend, o pen the applicatio n we created in the "Using the Visual Studio Binding Dialo g" sectio n. The easiest way is to right-click MainPage.xaml in the Visual Studio So lutio n Explorer and select Open in Expression Blend from the co ntext menu. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    2. In Blend, select the TextBo x and o pen the Properties panel. 3. No tice that the Te xt property's value is surrounded by an orange border. Also, the small peg next to the value is orange, to o . 4. Click the peg and select Data Binding from the co ntext menu. This opens the editor show n in Figure 6.5. In fact, similar to w hat yo u saw earlier in Visual Studio, a visual ind icatio n for the property value's origin is coded in Blend, as show n in Figure 6.4.

    FIGURE 6 .4 Property origin: Inherited/ Default/ Style, Local, Resource, Binding.

    Creat e Dat a Umfing ill Iret Borl Trrt to ExpfcuL Data Conlrrt

    Element Piepnly Prnpfft ifi

    | j f l r t wi f r t l 7f ; • ilrfidrrTtnmf arm : [Trnndortn) • JlfiuJrfTEamlarnOngm ! (Paint)

    Note that unlike in Visual Studio, Expression Blend does no t differentiate betw een a value being set thro ugh inheritance, by default, or thro ugh a style.

    I

    i- N KBU i m [Arr.iy] : [Re t nurrr Dir t iaiu

    - M >lr:rJ|*) toblndcot: pnUïJ labM wigabon : (KeyboardM wigationM ode) lag : [Ubjed) • remploie : [C.on1rolUr&pmet » f rigqt u tAiTBri : 4lrlQQH tsromlaL

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA



    In listing 8.1, lines 1 to 7 set the Da t a Gr i d 's p ro p erties. N o te o n line 7 the Aut oGe ne r a t e Col umns p ro p erty set to Fal s e. It m eans that the Da t a Gr i d co ntro l w ill no t attem p t to insp ect the items and create co lum ns auto matically . Lines 9 to 22 d efine the Da t a Gr i d 's Col umns co llectio n. Then, o n lines 10 and 11, a Da t a Gr i dTe xt Col umn is added. The He a de r set to " Las t

    name"

    w ill be d isplayed o n to p o f the c o lum n. The c o ntent o f the cell is b o u nd to the La s t Na me p ro p erty o f the Model . Because the imp licit Da t a Cont e xt o f the ro w is a Cus t ome r Vi e wMode l , this all falls into p lace. O n lines 12 and 13, the same is d o ne fo r the Cus t ome r 1 s Fi r s t Na me pro perty. O n lines 14 to 21, a m o re c o m p lex c o lu m n is d efined : The Da t a Gr i dTe mpl a t e Col umn allo w s creating a Da t a Te mpl a t e and d isplaying exactly w hat is need ed . In o ur case, the Da t a Te mpl a t e uses an I ma ge co ntro l w ith its Sour c e p ro p erty set to Model . Pi ct ur el l r i . Befo re the ap p licatio n can be tested , the Da t a Gr i d 's I t e ms Sour c e m ust be set. O ne o p tio n w o uld be to use the Cus t ome r s co llectio n directly. Ho w ever, this class is limited and w e w ant to co nfig ure the d ata fo r filtering and p aging. This is w hy a Pa ge dCol l e c t i onVi e w is p laced o n to p o f the data.

    Building t hezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Pa g e d Co l l e c t i o n V i e w The Pa ge dCol l e c t i onVi e w is lo cated in y et ano ther assembly. W e need to ad d the reference to this assembly m anually w ith the fo llo w ing steps: 1. In the So lutio n Explo rer, right-click the DataA p p licatio nSamp le p ro ject and select A dd Reference fro m the c o ntext m enu . 2 . In the A dd Reference d ialo g, cho o se the tab labeled Bro w se and nav ig ate to

    C:\Pro gram Files\Micro so ft SDKs\Silv erlight\v 4.0\Libraries\Client. This p ath is w here all the Silverlight assemblies are lo cated . O n W in 64 m achines, the fo ld er is in Pro gram Files (x86).

    Fi l t eri ng and Paging w i t h t h e P a g e d Co l l e c t i o n Vi e w

    191

    zyxwvutsrqponmlk

    3. Select the assembly nam ed Sy stem.W ind o w s.Data.d ll and click OK. This adds a reference to that assembly. N o te that the assembly w ill also be ad d ed to yo ur XA P file. This increases the size o f the file that need s to be d o w nlo ad ed to the w eb bro w ser,

    but at the same tim e it gives y o u access to thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDC Pa ge dCol l e c t i onVi e w and its features.

    4. In co ntrast to the Col l e c t i onVi e wSour c e , the Pa ge dCol l e c t i onVi e w class c anno t be d efined in XA ML d irectly because it d o es no t hav e a d efault co nstructo r. To create it, o p en the file M ainPag e.xaml.es in Visual Stud io . 5. M o d ify the Ma i nPa ge co nstructo r as sho w n in Listing 8. 2.

    L I STI N G 8 .2

    Building a P a g e d Co l l e c t i o n Vi e w

    publ i c Ma i nPa ge ( ) { I ni t i a l i z e Compone nt ( ) ; var s e r vi c e = new Cus t ome r Se r vi c e Pr oxyO ; var vm = new Ma i nVi e wMode l ( s e r vi c e ) ; Da t a Cont e xt = vm; var pev = new Pa ge dCol l e c t i onVi e w( vm. Cus t ome r s ) ; Cus t ome r s Da t a Gr i d. I t e ms Sour c e = pev;

    6. M ake sure that the p ro ject

    Last nam e

    First name

    Picture

    DataA p p licatio nSamp le.W eb is set as startup p ro ject in the So lutio n Explo rer. Its nam e sho uld appear in bo ld . If this is no t the case, the p ictures w o n' t be d isplayed because o f a p ermissio n issue. W e talked abo ut this in Silverlight 2 Unleashed,

    zyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA

    Chap ter 5, Table 5.3. To

    set the w eb ap p licatio n as startup, rig ht-click the DataA p p licatio nSamp le.W eb p ro ject and select Set as StartUp Pro ject fro m the c o ntext m enu .

    7. Run the ap p licatio n b y pressing Ctrl+F5. A fter a small delay, the Da t a Gr i d sho w s a list o f custo mers in three co lum ns: First nam e, Last nam e, and a p icture, as sho w n in Figure 8.1.

    FI GURE 8 .1 zyxwutsrponmlkjihgfedcbaWVUTSRPLIGFEDCB Dat aGr i d wit h list of cu st om ers.

    192

    CHAPTER 8

    Usi n g Dat a Co n t r o l s

    Fi l t er i n g Da t a zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA In this sectio n, the d ata sho uld be filtered befo re display. A fter running the ap p licatio n w e built in the p rev io us sectio n, so me ro w s appear w itho ut a p icture because the co rresp o nd ing p ro p erty is em p ty in the d atabase. In this sectio n, w e are build ing a filter that remo v es custo mers w itho ut a p icture w ith the fo llo w ing steps: 1. O p en M ainPag e.xam l in the Visual Stud io designer.

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHG

    2. W ith the Gr i d ( Layout Root ) selected , pass the m o use o n the side o f the grid until the curso r turns into a cross, as sho w n in Figure 8.2.

    i

    3. At abo ut 40 p ixels fro m the b o tto m , click to set a new FI GURE 8 .2 new row.

    ro w in the grid.

    Set t ing a

    4. The grid's new ro w appears in the d esigner w ith its heig ht in p ixels ind icated o n the side. Pass again the mo use near the ed ge o f the ro w until so me ico ns appear, as sho w n in Figure 8.3. The first ico n o n to p ind icates a fixed heig ht. Even w hen the w ind o w is resized, the ro w 's heig ht w ill no t chang e. This is w hat y o u sho uld click no w . The seco nd ico n ind icates a star heig ht. It m eans that the ro w w ill take the rest o f the heig ht after all o ther ro w s hav e been calculated . If y o u hav e tw o or m o re ro w s w ith a SD * zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM star size, y o u can set fo r instance 0.4* and 0.6* Land and the ro w s w ill be sized p ro p o rtio nally. As fo r 1 Aut o Row size is det er m ined by t he cont ends) j the last ico n o n the b o tto m , it ind icates an A uto size. The heig ht o f the ro w d ep end s o n FI GUR E 8 . 3 Set t ing t he row's w hat the ro w co ntains. If the ro w is empty, its height . heig ht w ill be set to zero . 5. Set the ro w to a fixed heig ht o f 40 p ixels. If need ed y o u can also chang e the v alue in XA ML. 6. Select the Da t a Gr i d and chang e its Gr i d. RowSpa n p ro p erty to 1 in the Pro perties edito r. This p ro p erty has been set to 2 auto m atically w hen the new ro w w as ad d ed . W e need to free so me space fo r the new UI elements. 7. Drag a check b o x fro m the To o lbo x o n the grid's new row . Set its p ro p erties so that it is aligned v ertically in the center o f the row . 8. Set the Cont e nt o f the check b o x to " Wi t h pi c t ur e s onl y" . 9. O n to p o f the Pro perties ed ito r, click the Events tab. Lo cate the Cl i c k ev ent; d o ubleclick in the field next to the ev ent's nam e. This adds a new ev ent hand ler to the co d e b ehind and o p ens the file M ainPag e.xaml.es. 10. Chang e the ev ent hand ler's co d e to reflect Listing 8.3.

    zyxwvutsrqponmlkjihgfedcbaYWVUTSRQPON

    Fi l t eri ng and Paging w i t h t h e P a g e d Co l l e c t i o n Vi e w

    L I STI N G 8 . 3

    Set t ing and Reset t ing t he Filter

    1 2 3

    pr i va t e voi d c he c kBox1_Cl i c k( obj e c t s e nde r , Sys t e m. Wi ndows . Rout e dEve nt Ar gs e)

    4

    {

    5 6 7

    193

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    va r c he c kbox = s e nde r as Che c kBox; va r pcv = Cus t ome r s Da t a Gr i d. I t e ms Sour c e as Pa ge dCol l e c t i onVi e w;

    9 10

    if

    11

    {

    12 13 14 15 16

    ( checkbox ! = nul l && pcv ! = nul l ) xuomlbQLKHEB if {

    ( c he c kbox. I s Che c ke d == t r ue ) pc v. Fi l t e r = c => { va r c us t ome r = c as Cus t ome r Vi e wMode l ; r e t ur n c us t ome r ! = nul l && c us t ome r . Mode l ! = nul l && c us t ome r . Mode l . Pi ct ur el l r i

    ! = nul l ;

    }; el s e { pc v. Fi l t e r = nul l ; 27

    }

    28

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    } • •

    O n line 5 w e get the send er o f the ev ent and cast it to a Che c kBox. O n lines 6 and 7, w e get the I t e ms Sour c e p ro p erty o f the Da t a Gr i d. It has been set to the Pa ge dCol l e c t i onVi e w into the Ma i nPa ge co nstructo r befo re. W e can cast this p ro p erty to a Pa ge dCol l e c t i onVi e w again.



    A fter m aking sure that the o bjects are no t nul l and are casted co rrectly w e query the state o f the Che c k box o n line 12.



    If the check b o x is checked , w e set the Fi l t e r p ro p erty o f the Pa ge dCol l e c t i onVi e w. The sy ntax used here is azyxwvutsrqponmlkjihgfedcbaXWVUTSRQPONMLKJIFEDCBA lambda expression. You alread y saw a lam bd a in Chap ter 7, Listing 7.9. The sy ntax here is a little bit d ifferent: W e hav e o nly o ne p arameter c (o f typ e obj ect ) , so w e can o m it the p arenthesis aro und the p arameter list.

    194

    CHAPTER 8

    Usi n g Dat a Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB

    • The filter blo ck is d efined after the arro w =>. The p arameterzyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONM c is casted to a

    Cus t ome r Vi e wMode l o n line 16. Then w e check w hether the p arameter is nul l , if its Mode l p ro p erty is nul l , and finally w hether the Pi ct ur el l r i p ro p erty is nul l . We o nly return t r ue if all three co nd itio ns are f al s e. •

    Finally, if the check b o x is no t checked , w e reset the filter to nul l o n line 25. This w ill auto m atically d isplay all the ro w s in the grid again.

    The framew o rk executes the filter m etho d w hen need ed to d ecid e w hich ro w s m ust be includ ed in the result. The nice thing is that ev ery thing here is d y namic: Thro ug h the Obs e r va bl e Col l e c t i on, the Pa ge dCol l e c t i onVi e w and the d ata bind ing to the Da t a Gr i d, every chang e to the co llectio n or to the filter w ill im m ed iately be reflected in the user interface. To test the filter, run the ap p licatio n, and then check/ uncheck the check b o x. The ro w s w itho ut a p icture d isappear w hen the check b o x is unchecked .

    Pa gi n g Th r o u gh Dat a As its nam e imp lies, the Pa ge dCol l e c t i onVi e w is also able to page thro ug h d ata. Paging is a great w ay to break the d ata into smaller chunks. This has the ad v antag e o f making the user interface m o re resp o nsiv e (because less d ata has to be lo ad ed befo re the user starts using the current page), and also m aking it easier fo r the user to find the ro w that he w ants to hand le. Paging is d o ne b y setting the p ro p erty Pa ge Si z e . The Pa ge dCol l e c t i onVi e w w ill auto matically d eliver a set o f d ata co rresp o nd ing to this pro perty. M o v ing thro ug h d ata is d o ne w ith the m etho d s Move ToFi r s t Pa ge , Move ToLa s t Pa ge , Move ToNe xt Pa ge , Move ToPr e vi ous Pa ge , and Move ToPa ge . The ev ents Pa ge Cha ngi ng and Pa ge Cha nge d are raised befo re and after the current page has chang ed , respectively, and the p ro p erty I s Pa ge Cha ngi ng is set to t r ue w hile the next page is calculated . This allo w s a co ntro l to d isplay a small anim atio n, fo r examp le. The Pa ge l nde x p ro p erty ind icates w hich page is currently d isplayed . To test p aging w ith the Da t a Gr i d, fo llo w these steps: 1. Reo p en the DataA p p licatio nSamp le so lutio n that w e used earlier in this chap ter.

    2. In M ainPag e.xaml.es, in the Ma i nPa ge co nstructo r, chang e the w ay that the Pa ge dCol l e c t i onVi e w is created acco rd ing to Listing 8.4. 3. Run the ap p licatio n. A fter the initial lo ad ing time, o nly tw o ro w s are d isplayed , acco rd ing to the page size.

    L I STI N G 8 . 4

    Set t ing t he Page Size

    va r pev = new Pa ge dCol l e c t i onVi e w( vm. Cus t ome r s ) ; pc v. Pa ge Si z e = 2; Cus t ome r s Da t a Gr i d. I t e ms Sour c e = pc v;

    Fi l t eri ng and Paging w i t h t h e P a g e d Co l l e c t i o n Vi e w

    195

    zyxwvutsrqponmlk

    N o te the fo llo w ing : •

    Even tho ug h o nly tw o ro w s are d isplayed , the initial lo ad ing tim e is the same as w hen all the ro w s w ere sho w n. The p aging o ccurs o n the client after all the d ata has been lo ad ed fro m the server.

    • There is currently no w ay to m o v e to the next page. A d d itio nal user interface elem ents are need ed to m o v e thro ug h the pages. This co uld be d o ne b y ad d ing a few b u tto ns and text bo xes, but there is also a c o nv enient co ntro l that y o u w ill see a little later in this chap ter: thezyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Da t a Pa ge r co ntro l.

    Op t i m i zi n g Da t a Ha n d l i n g The Pa ge dCol l e c t i onVi e w is v ery useful w ith c o m p lex d ata co ntro ls, but it also co m es w ith a cav eat: W h e n y o u w o rk w ith really large sets o f data, it can be m o re efficient to imp lem e nt p aging o n the server than o n the client. Client-sid e p aging imp lies that m o st o f the d ata w ill be lo ad ed initially befo re the user interface is sho w n to the user. This initial lo ad ing tim e can be v ery im p o rtant and cause the ap p licatio n to take a lo ng tim e to appear. A lso, hav ing the w ho le d ata o n the client requires a lo t o f memo ry , w hic h can be a p ro blem o n so me limited p latfo rms. O n the o ther hand , o f co urse, hav ing the w ho le d ata o n the client makes the ap p licatio n m o re resp o nsiv e after it has been lo ad ed (because there are few er client-serv er interactio ns). Chap ters 13 and 14 exam ine a w ay to build ap p licatio ns that get fro m the server o nly the am o u nt o f d ata need ed , alread y so rted . As usual in so ftw are d ev elo p ment, the right techno lo g y to cho o se d ep end s o n w hat yo ur scenario is.

    T I P zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Using Endless Scrolling Som e dat a grids su ch as t he one developed by XCeed offer en d l ess scrolling: Once t he user reaches t he bot t om of t he loaded set of dat a, t he grid aut om at ically f et ches m ore dat a and adds t hem t o t he display. Thi s prevent s t he need t o click on a " previous page" or " next page" but t on. Thi s al so sp eed s up t he act ion beca use only t he am ount of dat a t hat is needed is kept in m em ory (dat a virt ualizat ion). Such a grid can be seen in act ion at ht t p:/ / dem o.xceed.com / Dat aGri d_Si l verl i ght / Dem o/ . \

    Im p l em en t i n g Cu st o m So r t i n g The Cus t ome r class returned b y the W C F service has a Ge nde r pro perty. The v alue is taken fro m an enum eratio n w ith five p o ssible v alues: Mal e, Femal e, Boy, Gi r l , and Unknown. It w o uld be nice to be able to so rt acco rd ing to the gend er (fo r examp le, Fe ma l e and Gi r l first, then Ma l e and Boy, and finally Unknown) .

    /

    196

    CHAPTER 8

    Usi n g Dat a Co n t r o l s

    zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCB

    Unfo rtunately , custo m so rting requires quite so me m anu al w o rk. You can find a g o o d d escrip tio n abo ut ho w to build a co llectio n allo w ing custo m so rting can be fo und at http:/ / w w w .galaso ft.ch/ sl4-so rting. zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA

    Adding a zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA Da t a Pa ge n Control In the p reced ing sectio n, y o u saw ho w to prepare a Pa ge dCol l e c t i onVi e w fo r p aging, but d id y o u also no tic e that so m ething w as missing ? The Da t a Gr i d alo ne c anno t page thro ug h the d ata. A d d itio nal UI elem ents are need ed to d isplay the d ata acco rd ing to the user's need s. O ne p o ssibility is to create a custo m user interface and to use the p aging-related m etho d s, p ro p erties, and ev ents in the Pa ge dCol l e c t i onVi e w class. How ever, an easier w ay exists, w ith the Da t a Pa ge r co ntro l (available in the same assembly as the Da t a Gr i d: Sy stem.W ind o w s.Co ntro ls.Data.d ll), sho w n in Figure 8.4. This co ntro l can be ad d ed to o ur ap p licatio n w ith the fo llo w ing steps: 1. O p en the So rtingA nd Fitering ap p licatio n in VisualStud io .

    2. O p en the file M ainPag e.xaml in the XA ML edito r. 3. M o d ify the RowDe f i ni t i ons o f the Gr i d as sho w n in Listing 8. 5.

    LI STI NG 8 . 5

    Cr eat i ng a Ne w Ro w



    4. A fter the Che c kBox at the end o f the Gr i d, add a Da t a Pa ge r co ntro l as sho w n in Listing 8.6.

    LI STI NG 8. 6

    Addi ng a Da t a Pa ge r Cont r ol

    As sho w n in Listing 8.6, ad d ing the Da t a Pa ge r is really v ery easy. The o nly p ro p erty that is really need ed is the Sour c e p ro p erty that m ust be set to the same I Enume r a bl e as the

    Da t a Gr i d 's I t e ms Sour c e pro perty. O nce this is d o ne, run the ap p licatio n. You sho uld see the Da t a Pa ge r at the b o tto m o f the page. Because w e set the Pa ge Si z e to 2 in Listing 8.4, o nly tw o ro w s o f d ata are d isplayed .

    Va l i d a t i n g Dat a Input

    197

    zyxwvutsrqponmlk

    To nav ig ate to a d ifferent page, the b u tto ns can be used (fro m left to right): Go to the first page, go to the p rev io us page, go to any page acco rd ing to an ind ex, go to the next page, and go to the last page.

    Cu st o m i zi n g t h e Di sp l a y

    The d efault d isplay can be custo miz ed using so me p ro p erties and styles. ThezyxwvutsrqponmlkjihgfedcbaZYXWVUTS Di s pl a yMode p ro p erty can be set to v ario us values, as sho w n in Figure 8.4 (co p ied fro m the Silv erlight d o cum entatio n). W h e n used w ith num eric butto ns, ad d itio nal pro per-

    Aut uEjllpsis = Tr ue

    ties can be used to custo miz e the lo o k and feel o f the

    1

    co ntro l:

    DisplayM ode = Fir st Last Num er r c





    Nume r i c But t onCount is used to set ho w m any num eric b utto ns are sho w n in the co ntro l.

    14 1 I

    14 1 1

    1

    2

    3

    4

    ..

    H

    3

    4

    S

    >1

    DisplayM ode = Fl r st Last Pr evl o u sNext M

    zyxwvutsrqponmlkjihgfedcbaXWVUTSRQP < j Page | 1 10 > H

    Nume r i c But t onSt yl e can be set to a St yl e and

    DisplayM ode •

    allo w s m o d ify ing the ap p earance o f the num eric

    1

    b u tto ns w itho ut hav ing to chang e the style and

    DisplayM ode •

    tem p late o f the w ho le Da t a Pa ge r co ntro l. The

    1

    num eric b utto ns are Toggl e But t on co ntro ls, so

    DisplayM ode = Pr evJousNpxt

    the co rresp o nd ing typ e m ust be used fo r the style

    1

    (and the tem p late if so d esired ).

    2

    Flr st Last Pr evlo u sNeKt Nu m er lc l