Tải bản đầy đủ (.pdf) (834 trang)

Pro Silverlight 3 in C# docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (26.47 MB, 834 trang )

MacDonald
Silverlight 3 in C#
Companion
eBook Available
trim = 7" x 9.125" spine = 1.90625" 832 page count
The eXPeRT’s VOIce
®
In sIlVeRlIghT
Pro
Silverlight 3
in C#
Matthew MacDonald
Create cross-platform .NET applications for the browser
Full Color Inside
Full Color Inside
Pro
this print for content only—size & color not accurate
BOOks fOR PROfessIOnals By PROfessIOnals
®
Pro Silverlight 3 in C#
Dear Reader,
Silverlight is a revolutionary browser plug-in that allows developers to create
rich client applications that run inside the browser. Like Adobe Flash, Silverlight
supports event handling, two-dimensional drawing, video playback, network-
ing, and animation. Unlike Flash, Silverlight is tailored to .NET developers.
Most impressively, Silverlight applications execute pure C# code.
The most exciting part of Silverlight is its cross-platform muscle. Unlike
ordinary .NET applications, Silverlight applications run seamlessly in non-
Microsoft browsers (like Firefox) and on non-Microsoft platforms (like Mac OS
X). Essentially, Silverlight is a scaled-down, browser-hosted version of .NET—
and that’s made it the most hotly anticipated technology that Microsoft’s


released in years.
In this book, you’ll master Silverlight from the ground up. No Silverlight
experience is required—but if you’ve worked with Silverlight 2, you’ll appreci-
ate the “What’s New” boxes that point out new features at the start of every
chapter. By the end of this book, you’ll have a solid understanding of the com-
plete Silverlight platform, and you’ll be able to build anything from a slick busi-
ness front-end to a browser-based game.

Welcome aboard!

Matthew MacDonald
MCSD, Microsoft Silverlight MVP

US $49.99
Shelve in
Web Development
User level:
Intermediate - Advanced
cyan
MagenTa
yellOW
Black
PanTOne 123 c
Pro Business Applications
with Silverlight 3
THE APRESS ROADMAP
Pro Silverlight 3
for the Enterprise
Pro
Silverlight 3 in C#

Beginning
Silverlight 3
Accelerated
Silverlight 3
Silverlight
Recipes
www.apress.com
SOURCE CODE ONLINE
)3".
  
   
Author of
Pro WPF in C# 2008
Pro ASP.NET 3.5 in C# 2008
(with Mario Szpuszta)
Beginning ASP.NET 3.5 in
C# 2008
Pro Silverlight 2 in C# 2008
Your Brain: The Missing
Manual
Companion eBook

See last page for details
on $10 eBook version
www.it-ebooks.info



www.it-ebooks.info


i


Pro Silverlight 3 in C#




■ ■ ■
Matthew MacDonald


www.it-ebooks.info

ii


www.it-ebooks.info

iii
Pro Silverlight 3 in C#
Copyright © 2009 by Matthew MacDonald
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN-13 (pbk): 978-1-4302-2281-8
ISBN-13 (electronic): 978-1-4302-2382-5
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every

occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
Lead Editor: Ewan Buckingham
Technical Reviewer: Damien Foggon
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony
Campbell, Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey
Pepper, Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom
Welsh
Coordinating Editor: Anne Collett
Copy Editor: Heather Lang and Tiffany Taylor
Associate Production Director: Kari Brooks-Copony
Production Editor: Brigid Duffy
Compositor: Nancy Wright
Indexer: John Collin
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-
, or visit .
For information on translations, please e-mail , or visit .
Apress and friends of ED books may be purchased in bulk for academic, corporate, or
promotional use. eBook versions and licenses are also available for most titles. For more
information, reference our Special Bulk Sales—eBook Licensing web page at

The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.
The source code for this book is available to readers at . You will need to
answer questions pertaining to this book in order to successfully download the code.



www.it-ebooks.info

iv


For my family


www.it-ebooks.info

v
Contents at a Glance
■About the Author xxii
■About the Technical Reviewer xxii
■Acknowledgments xxiv
■Introduction xxv
■Chapter 1: Introducing Silverlight 1
■Chapter 2: XAML 33
■Chapter 3: Layout 61
■Chapter 4:Dependency Properties and Routed Events 107
■Chapter 5: Elements 135
■Chapter 6: The Application Model 183
■Chapter 7: Navigation 227
■Chapter 8: Shapes and Geometries 253
■Chapter 9: Brushes, Transforms,and Bitmaps 291
■Chapter 10: Animation 325
■Chapter 11: Sound, Video, and Deep Zoom 387
■Chapter 12: Styles and Behaviors 425

■Chapter 13: Templates and Custom Controls 449
■Chapter 14: Browser Integration 491
■Chapter 15: ASP.NET Web Services 517
■Chapter 16: Data Binding 541
■Chapter 17: Data Controls 585
■Chapter 18: Isolated Storage 635
■Chapter 19: Multithreading 657
■Chapter 20: Networking 679
■Index 727

www.it-ebooks.info

www.it-ebooks.info

vii
Contents

■About the Author xxii
■About the Technical Reviewer xxiii
■Acknowledgments xxiv
■Introduction xxv
Understanding Silverlight 9
Silverlight System Requirements 12
Silverlight vs. Flash 12
Silverlight and WPF 14
The Evolution of Silverlight 15
About This Book 17
What You Need to Use This Book 17
The Silverlight Toolkit 18
Code Samples 19

Feedback 19
The Last Word 19
■Chapter 1: Introducing Silverlight 1
Silverlight Design Tools 1
Visual Studio vs. Expression Blend 2
Understanding Silverlight Websites 3
Creating a Stand-Alone Silverlight Project 4
Creating a Simple Silverlight Page 7
Adding Event Handling Code 9
Testing a Silverlight Application 11
Creating an ASP.NET-Hosted Silverlight Project 12
ASP.NET Controls That Render Silverlight Content 16
Mixing ASP.NET Controls and Silverlight Content 17
Silverlight Compilation and Deployment 17
Compiling a Silverlight Application 17
Deploying a Silverlight Application 19
Silverlight Core Assemblies 21
www.it-ebooks.info
■ CONTENTS

viii
Silverlight Add-On Assemblies 22
Assembly Caching 23
The HTML Entry Page 25
Sizing the Silverlight Content Region 27
Silverlight Parameters 27
Alternative Content 29
Creating a Friendly Install Experience 29
The Mark of the Web 30
The Last Word 31

■Chapter 2: XAML 33
XAML Basics 34
XAML Namespaces 34
Core Silverlight Namespaces 35
Design Namespaces 36
Custom Namespaces 37
The Code-Behind Class 38

Naming Elements 39
Properties and Events in XAML 39
Simple Properties and Type Converters 41
Complex Properties 42
Attached Properties 44
Nesting Elements 45
Events 48
The Full Eight Ball Example 49
XAML Resources 50
The Resources Collection 50
The Hierarchy of Resources 51
Accessing Resources in Code 53
Organizing Resources with Resource Dictionaries 54
Element-to-Element Binding 56
One-Way Binding 56
Two-Way Binding 57
The Last Word 59
■Chapter 3: Layout 61
The Layout Containers 61
The Panel Background 63
Borders 65
Simple Layout with the StackPanel 66

Layout Properties 68
Alignment 69
www.it-ebooks.info
■ CONTENTS

ix
Margins 70
Minimum, Maximum, and Explicit Sizes 72
The WrapPanel and DockPanel 74
The WrapPanel 74
The DockPanel 76
The Grid 77
Fine-Tuning Rows and Columns 79
Nesting Layout Containers 80
Spanning Rows and Columns 82
The GridSplitter 83
Coordinate-Based Layout with the Canvas 87
Layering with ZIndex 88
Clipping 89
Custom Layout Containers 90
The Two-Step Layout Process 91
MeasureOverride() 91
ArrangeOverride() 92
The UniformGrid 93

Sizing Pages 98
Scrolling 100
Scaling 102
Full Screen 105
The Last Word 106

■Chapter 4: Dependency Properties and Routed Events 107
Dependency Properties 107
Defining and Registering a Dependency Property 108
Dynamic Value Resolution 110
Attached Properties 111
The WrapBreakPanel Example 112
Routed Events 115
The Core Element Events 115
Event Bubbling 118
Handled (Suppressed) Events 119
An Event Bubbling Example 120
Mouse Movements 123
The Mouse Wheel 123
Capturing the Mouse 125
A Mouse Event Example 126
Mouse Cursors 129
Key Presses 130
Key Modifiers 132
www.it-ebooks.info
■ CONTENTS

x
Focus 133
The Last Word 134
■Chapter 5: Elements 135
The Silverlight Elements 135
Static Text 140
Font Properties 141
Standard Fonts 142
Font Embedding 143

Underlining 145

Runs 145
Wrapping Text 146
Images 147
Image Sizing 148
Image Errors 149
Content Controls 149
The Content Property 151
Aligning Content 153
Buttons 154
The HyperlinkButton 155
The ToggleButton and RepeatButton 155
The CheckBox 156
The RadioButton 156
Tooltips and Pop-Ups 158
Customized ToolTips 158
The Popup 160
Items Controls 162
The ListBox 162
The ComboBox 165
The TabControl 165
Text Controls 167
Text Selection 168
The PasswordBox 168
The AutoCompleteBox 169
Filter Mode 170
Custom Filtering 171
Dynamic Item Lists 173
Range-Based Controls 175

The Slider 176
The ProgressBar 176
Date Controls 177
www.it-ebooks.info
■ CONTENTS

xi
The Last Word 181
■Chapter 6: The Application Model 183
The Application Class 183
Accessing the Current Application 184
Application Properties 184
Application Events 185
Application Startup 186
Initialization Parameters 187
Application Shutdown 190
Unhandled Exceptions 190
Custom Splash Screens 192
Out-of-Browser Applications 197
Enabling Out-of-Browser Support 199
Installing an Out-of-Browser Application 201
Customizing Icons 203
Tracking Application State 204
Removing and Updating an Application 208
Binary Resources 209
Placing Resources in the Application Assembly 210
Using Subfolders 212
Programmatically Retrieving a Resource 212
Placing Resources in the Application Package 213
Placing Resources on the Web 214

Failing to Download Resources 215
Downloading Resources with WebClient 216
Class Library Assemblies 218
Using Resources in an Assembly 218
Downloading Assemblies on Demand 219
Supporting Assembly Caching 220
The Strong Key Name 221
The .extmap.xml File 222
The Last Word 225
■Chapter 7: Navigation 227
Loading User Controls 228
Embedding User Controls in a Page 228
Hiding Elements 230
Managing the Root Visual 230
Retaining Page State 231
Browser History 233
Child Windows 233
www.it-ebooks.info
■ CONTENTS

xii
Designing a ChildWindow 235
Showing a ChildWindow 236
The Frame and Page 238
Frames 238
Browser URI Integration 241
History Support 243
URI Mapping 244

Forward and Backward Navigation 246

Hyperlinks 247
Pages 247
Navigation Properties 248
State Storage 249
Navigation Methods 249
Navigation Templates 250

The Last Word 251
■Chapter 8: Shapes and Geometries 253
Basic Shapes 253
The Shape Classes 254
Rectangle and Ellipse 255
Sizing and Placing Shapes 257
Sizing Shapes Proportionately with a Viewbox 260
Line 262
Polyline 263
Polygon 264
Line Caps and Line Joins 267
Dashes 269
Paths and Geometries 271
Line, Rectangle, and Ellipse Geometries 272
Combining Shapes with GeometryGroup 273
Curves and Lines with PathGeometry 274
Straight Lines 276
Arcs 276
Bézier Curves 278
The Geometry Mini-Language 280

Clipping with Geometry 282
Exporting Clip Art 284

Expression Design 284
Conversion 286
Save or Print to XPS 286
The Last Word 289
www.it-ebooks.info
■ CONTENTS

xiii
■Chapter 9: Brushes, Transforms,and Bitmaps 291
Brushes 291
The LinearGradientBrush Class 292
The RadialGradientBrush Class 295
The ImageBrush 297
Transparency 298
Opacity Masks 301
Making the Silverlight Control Transparent 302
Transforms 305
Transforming Shapes 307
Transforms and Layout Containers 309
A Reflection Effect 310
Perspective Transforms 312
The PlaneProjection Class 313
Applying a Projection 314
Pixel Shaders 316
BlurEffect 317
DropShadowEffect 317
ShaderEffect 319
The WriteableBitmap Class 320
Generating a Bitmap 320
Capturing Content from Other Elements 322

The Last Word 323
■Chapter 10: Animation 325
Understanding Silverlight Animation 325
The Rules of Animation 327
Creating Simple Animations 328
The Animation Class 328
The Storyboard Class 328
Starting an Animation with an Event Trigger 329
Starting an Animation with Code 330
Configuring Animation Properties 331
From 331
To 333
By 333
Duration 333
Animation Lifetime 334

RepeatBehavior 335
Simultaneous Animations 336

Controlling Playback 337
www.it-ebooks.info
■ CONTENTS

xiv
Animation Easing 339
Using an Easing Function 340
Easing In and Easing Out 341
Easing Function Classes 342
Animation Types Revisited 346
Animating Transforms 346

Animation Perspective Projections 349
Animating Brushes 351
Animating Pixel Shaders 352
Key-Frame Animation 353
Discrete Key Frames 355
Easing Key Frames 355
Spline Key Frames 356
Animations in Code 357
The Main Page 359
The Bomb User Control 360
Dropping the Bombs 362
Intercepting a Bomb 365
Counting Bombs and Cleaning Up 366
Encapsulating Animations 368
Page Transitions 369
The Base Class 370
The Wipe Transition 372
Frame-Based Animation 374
Animation Performance 378
Desired Frame Rate 378
Hardware Acceleration 379
Enabling Hardware Acceleration 380
Bitmap Caching 380
Evaluating Hardware Acceleration 383
The Last Word 385
■Chapter 11: Sound, Video, and Deep Zoom 387
Supported File Types 387
The MediaElement 388
Controlling Playback 389
Handling Errors 390

Playing Multiple Sounds 390
Changing Volume, Balance, and Position 391
Playing Video 395
Client-Side Playlists 396
Server-Side Playlists 396
www.it-ebooks.info
■ CONTENTS

xv
Progressive Downloading and Streaming 397
Adaptive Streaming 399
Advanced Video Playback 400
Video Encoding 400
Encoding in Expression Encoder 401
Markers 403
Adding Markers with Expression Encoder 403
Using Markers in a Silverlight Application 405
VideoBrush 408

Video Effects 409
Deep Zoom 414
Creating a Deep Zoom Image Set 416
Using a Deep Zoom Image Set in Silverlight 419
The Last Word 423
■Chapter 12: Styles and Behaviors 425
Styles 425
Defining a Style 426
Applying a Style 427
Dynamic Styles 428
Style Inheritance 429

Organizing Styles 430
Behaviors 431
Getting Support for Behaviors 432
Triggers and Actions 432
Creating an Action 433
Connecting an Action to an Element 435
Design-Time Behavior Support in Blend 436
Creating a Targeted Trigger 439
Creating a Behavior 443

Finding More Behaviors 446
The Last Word 448
■Chapter 13: Templates and Custom Controls 449
Template Basics 449
Creating a Template 450
Reusing Control Templates 451
The ContentPresenter 452
Template Bindings 452
Setting Templates through Styles 454
Reusing Colors 455
The Parts and States Model 456
Understanding States with the Button Control 457
www.it-ebooks.info
■ CONTENTS

xvi
Showing a Focus Cue 462
Transitions 463
The Default Transition 464
From and To Transitions 465

Transitioning to a Steady State 466
Custom Transition 466
Understanding Parts with the Slider Control 468

Creating Templates for Custom Controls 472
Planning the FlipPanel Control 473
Creating the Solution 474
Starting the FlipPanel Class 474
Adding the Default Style with Generic.xaml 476
Choosing Parts and States 478
Starting the Default Control Template 480
The FlipButton Control 481
Defining the State Animations 482
Wiring Up the Elements in the Template 484
Using the FlipPanel 486
Using a Different Control Template 487
The Last Word 489
■Chapter 14: Browser Integration 491
Interacting with HTML Elements 492
Getting Browser Information 493
The HTML Window 494
Popup Windows 495
Inspecting the HTML Document 496
Manipulating an HTML Element 498
Inserting and Removing Elements 501
Changing Style Properties 502
Handling JavaScript Events 503

Code Interaction 505
Calling Browser Script from Silverlight 506

Calling Silverlight Methods from the Browser 506
Instantiating Silverlight Objects in the Browser 509
Combining Silverlight and HTML Content 510
Sizing the Silverlight Control to Fit Its Content 511
Placing the Silverlight Control Next to an HTML Element 512
Securing HTML Interoperability 515
The Last Word 516
■Chapter 15: ASP.NET Web Services 517
Building Web Services for Silverlight 517
www.it-ebooks.info
■ CONTENTS

xvii
Creating a Web Service 518
Adding a Service Reference 519
Calling the Web Service 521
Configuring the Web Service URL 524
Web Service Data Types 526
More Advanced Web Services 527
Cross-Domain Web Service Calls 528
Monitoring the Network Connection 530
Using ASP.NET Platform Services 531
Duplex Services 533
Configuring the Service 534
The Interfaces 535
The Service 536
The Client 537
The Last Word 539
■Chapter 16: Data Binding 541
Binding to Data Objects 542

Building a Data Object 542
Displaying a Data Object with DataContext 543
Storing a Data Object as a Resource 546
Editing with Two-Way Bindings 547
Validation 548
ValidatesOnException 548
NotifyOnValidationError 551
The Validation Class 552
Change Notification 553

Building a Data Service 554
Calling the Data Service 557
Binding to a Collection of Objects 559
Displaying and Editing Collection Items 559
Inserting and Removing Collection Items 563
Binding to a LINQ Expression 564
Master-Details Display 567
Data Conversion 570
Formatting Strings with a Value Converter 570
Creating Objects with a Value Converter 574
Applying Conditional Formatting 577
Data Templates 579
Separating and Reusing Templates 581
More Advanced Templates 581
Changing Item Layout 583
www.it-ebooks.info
■ CONTENTS

xviii
The Last Word 584

■Chapter 17: Data Controls 585
Better Data Forms 586
The Goal: Data Class Markup 586
The Label 587
The DescriptionViewer 589
The ValidationSummary 590
Data Annotations 593
Raising Annotation Errors 593
The Annotation Attributes 595
Required 595
StringLength 595
Range 596
RegularExpression 596
CustomValidation 599
Web Service Type Sharing 601

Identifying Your Data Classes 601
Setting Up the Visual Studio Solution 602
The DataGrid 604
Creating a Simple Grid 605
Resizing and Rearranging Columns 607
Defining Columns 608
The DataGridCheckBoxColumn 610
The DataGridTemplateColumn 610
Formatting and Styling Columns 612

Formatting Rows 614
Row Details 616
Freezing Columns 617
Selection 618

Sorting 619
DataGrid Editing 620
Editing with Templates 620
Validation and Editing Events 621
The PagedCollectionView 624
Sorting 625
Filtering 625
Grouping 626
Paging 628
The TreeView 631
Filling a TreeView 631
A Data-Bound TreeView 632
www.it-ebooks.info
■ CONTENTS

xix
The Last Word 634
■Chapter 18: Isolated Storage 635
Understanding Isolated Storage 635
The Scope of Isolated Storage 636
What to Put in Isolated Storage 636
Using Isolated Storage 637
Opening an Isolated Store 637
File Management 637
Writing and Reading Data 638
Requesting More Space 640
Storing Objects with XmlSerializer 643
Storing Application Settings 646
The File Dialogs 647
Reading Files with OpenFileDialog 648

Writing Files with SaveFileDialog 650
Transmitting Files with a Web Service 650
The File Service 651
The Silverlight Client 654
The Last Word 656
■Chapter 19: Multithreading 657
Understanding Multithreading 657
The Goals of Multithreading 658
The DispatcherTimer 659
The Thread Class 659
Marshalling Code to the User Interface Thread 661
Creating a Thread Wrapper 664
Creating the Worker Class 665
Using the Thread Wrapper 667
Cancellation Support 668
The BackgroundWorker 670
Creating the BackgroundWorker 671
Running the BackgroundWorker 671
Tracking Progress 674
Supporting Cancellation 676
The Last Word 678
■Chapter 20: Networking 679
Interacting with the Web 679
Cross-Domain Access 680
HTML Scraping 682
REST and Other Simple Web Services 686
www.it-ebooks.info
■ CONTENTS

xx

Processing Different Types of Data 690
XML 690
Services That Return XML Data 691
Navigating Over an XDocument 694
Querying an XDocument with LINQ 696
Services That Require XML Data 698

Services That Return SOAP Data 701
Services That Return JSON Data 701
RSS 704
Sockets 707
Understanding Sockets and TCP 707
The Policy Server 709
The Policy File 710
The PolicyServer Classes 710
The PolicyConnection Classes 713
The Messaging Server 714

The Messenger Client 718
Connecting to the Server 718
Sending Messages 721
Receiving Messages 722
Local Connections 723
Sending a Message 724
Receiving a Message 725
The Last Word 726
■Index 727
www.it-ebooks.info
xxi
www.it-ebooks.info

■ CONTENTS

xxii
About the Author
■Matthew MacDonald is an author, educator, and Microsoft MVP for Silverlight. He’s the
author of more than a dozen books about .NET programming, including Pro WPF in C# (Apress,
2008), Pro ASP.NET 3.5 in C# (Apress, 2007), and the previous edition of this book, Pro
Silverlight 2 in C# (Apress, 2009). He lives in Toronto with his wife and two daughters.

www.it-ebooks.info
■ CONTENTS

xxiii
About the Technical Reviewer
■Damien Foggon is a developer, writer, and technical reviewer in cutting-edge technologies
and has contributed to more than 50 books on .NET, C#, Visual Basic and ASP.NET. He is a
multiple MCPD in .NET 2.0 and .NET 3.5 and can be found online at
.
www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×