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

pro silverlight 4 in c#

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 (19.68 MB, 913 trang )

MacDonald
Companion
eBook Available
this print for content only—size & color not accurate
  CYAN
  MAGENTA
  YELLOW
  BLACK
  PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Pro Silverlight 4 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 and
supports 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, Safari, and Chrome) 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 technol-
ogy that Microsoft has 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 3, 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
Matthew MacDonald,
author of
Pro WPF in C# 2010
Pro ASP.NET 4 in C# 2010
(with Adam Freeman and
Mario Szpuszta)
Beginning ASP.NET 4 in
C# 2010
Your Brain: The Missing
Manual
US $49.99
Shelve in
Web Design/General
User level:
Intermediate - Advanced
THE APRESS ROADMAP
Pro
Telerik ASP.NET and
Silverlight Controls
Pro
Business Applications
with Silverlight 4
Pro
Silverlight 4 in C#
Pro
WPF in C# 2010
Introducing
Silverlight 4

Beginning
Silverlight 4 in C#
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-2979-7
9 781430 229797
5 49 9 9
Silverlight 4 in C#
Full Color Inside
Pro
7 x 9.125 spine = 2.09375" 912 page count
THE EXPERT’S VOICE
®
 IN SILVERLIGHT
Pro
Silverlight 4
in C#
Matthew MacDonald
Create cross-platform .NET applications for the browser
Full Color Inside
www.it-ebooks.info
www.it-ebooks.info





Pro Silverlight 4 in C#















■ ■ ■
Matthew MacDonald



www.it-ebooks.info
Pro Silverlight 4 in C#
Copyright © 2010 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 the publisher.
ISBN-13 (pbk): 978-1-4302-2529-2979-7
ISBN-13 (electronic): 978-1-4302-2980-3
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1

Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or
not they are subject to proprietary rights.
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Technical Reviewer: Fabio Claudio Ferracchiati
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan
Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic
Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editors: Anne Collett and Debra Kelly
Copy Editor: Kim Wimpsett
Compositor: Mary Sudul
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring
Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
, or visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.
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
www.apress.com/info/bulksales.
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.
www.it-ebooks.info
For my family

www.it-ebooks.info
www.it-ebooks.info
■ CONTENTS
v
Contents at a Glance
■ Contents vi
■ About the Author xxii
■ About the Technical Reviewer xxiii
■ 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 141
■ Chapter 6: The Application Model 197
■ Chapter 7: Navigation 227
■ Chapter 8: Shapes and Geometries 259
■ Chapter 9: Brushes, Transforms, and Bitmaps 295
■ Chapter 10: Animation 339
■ Chapter 11: Sound, Video, and Deep Zoom 399
■ Chapter 12: Styles and Behaviors 447
■ Chapter 13: Templates and Custom Controls 471
■ Chapter 14: Browser Integration 513
■ Chapter 15: ASP.NET Web Services 539

■ Chapter 16: Data Binding 569
■ Chapter 17: Data Controls 619
■ Chapter 18: File Access 669
■ Chapter 19: Multithreading 695
■ Chapter 20: Networking 717
■ Chapter 21: Out-of-Browser Applications 767
■ Index 809

www.it-ebooks.info
■ CONTENTS

vi
Contents
■ Contents at a Glance v
■ About the Author xxii
■ About the Technical Reviewer xxiii
■ Acknowledgments xxiv
■ Introduction xxv
■ Chapter 1: Introducing Silverlight 1
Silverlight Design Tools 1

Visual Studio vs. Expression Blend 1
Understanding Silverlight Websites 2
Creating a Stand-Alone Silverlight Project 3

Creating a Simple Silverlight Page 6
Adding Event-Handling Code 8
Testing a Silverlight Application 10
Creating an ASP.NET-Hosted Silverlight Project 12
ASP.NET Controls That Render Silverlight Content 15

Mixing ASP.NET Controls and Silverlight Content 16
Silverlight Compilation and Deployment 16
Compiling a Silverlight Application 16
Deploying a Silverlight Application 18
Silverlight Core Assemblies 20
Silverlight Add-on Assemblies 21
Assembly Caching 22
The HTML Entry Page 24
Sizing the Silverlight Content Region 26
Silverlight Parameters 26
Alternative Content 28
Creating a Friendly Install Experience 28
www.it-ebooks.info
■ CONTENTS
vii
The Mark of the Web 30
The Last Word 31
■ Chapter 2: XAML 33
XAML Basics 34

XAML Namespaces 35
The Code-Behind Class 38
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
Margins 70
Minimum, Maximum, and Explicit Sizes 72
The WrapPanel and DockPanel 74
The WrapPanel 74
The DockPanel 75
www.it-ebooks.info
■ CONTENTS

viii
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 86
Layering with ZIndex 88
Clipping 88
Custom Layout Containers 90
The Two-Step Layout Process 90
The UniformGrid 93
Sizing Pages 98
Scrolling with the ScrollViewer 100
Scaling with the Viewbox 102
Full-Screen Mode 104
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 120
An Event Bubbling Example 120
Mouse Handling 123
Right-Clicks 123
Mouse Movements 124
The Mouse Wheel 124
Capturing the Mouse 126
A Mouse Event Example 127
Mouse Cursors 130

www.it-ebooks.info
■ CONTENTS
ix
Keyboard Handling 131
Key Presses 131
Key Modifiers 134
Focus 135
The Command Model 136
Building a Command 137
Connecting a Command 138
The Last Word 140
■ Chapter 5: Elements 141
The Silverlight Elements 141

Static Text 145
Font Properties 146
Underlining 150
Runs 151
Wrapping Text 152
Trimming Text 153
Images 153
Image Sizing 154
Image Errors 155
Content Controls 155
The Content Property 157
Aligning Content 159
Buttons 160
The HyperlinkButton 160
The ToggleButton and RepeatButton 161
The CheckBox 161

The RadioButton 162
Tooltips and Pop-Ups 163
Customized Tooltips 163
The Popup 165
Items Controls 167
The ListBox 167
The ComboBox 169
The TabControl 170
www.it-ebooks.info
■ CONTENTS
x
Text Controls . 171
The TextBox. 172
The PasswordBox. 174
The AutoCompleteBox . 174
The RichTextBox . 180
Range-Based Controls . 191
The Slider. 191
The ProgressBar . 192
Date Controls . 192
The Last Word . 196
■ Chapter 6: The Application Model 197
The Application Class . 197
Accessing the Current Application 198
Application Properties. 198
Application Events . 199
Application Startup. 200
Initialization Parameters 200
Application Shutdown. 204
Unhandled Exceptions 204

Custom Splash Screens 206
Binary Resources. 211
Placing Resources in the Application Assembly. 211
Placing Resources in the Application Package . 214
Placing Resources on the Web 215
Class Library Assemblies . 219
Using Resources in an Assembly 219
Downloading Assemblies on Demand 220
Supporting Assembly Caching 221
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
www.it-ebooks.info
■ CONTENTS
xi
Retaining Page State 232
Browser History 233
Child Windows 233
Designing a ChildWindow 235
Showing a ChildWindow 236
The Frame and Page 238
Frames 238
URI Mapping 245
Forward and Backward Navigation 246
Hyperlinks 247
Pages 248
Navigation Templates 251

Custom Content Loaders 252
Authentication and Navigation 253
Creating a Custom Content Loader 254
Using the Custom Content Loader 256
The Last Word 257
■ Chapter 8: Shapes and Geometries 259
Basic Shapes 259

The Shape Classes 260
Rectangle and Ellipse 261
Sizing and Placing Shapes 263
Sizing Shapes Proportionately with a Viewbox 265
Line 267
Polyline 268
Polygon 269
Line Caps and Line Joins 272
Dashes 274
Paths and Geometries 276
Line, Rectangle, and Ellipse Geometries 277
Combining Shapes with GeometryGroup 278
Curves and Lines with PathGeometry 280
The Geometry Mini-Language 286
Clipping with Geometry 288
www.it-ebooks.info
■ CONTENTS

xii
Exporting Clip Art 289
Expression Design 289
Conversion 291

Save or Print to XPS 291
The Last Word 294
■ Chapter 9: Brushes, Transforms, and Bitmaps 295
Brushes 295

The LinearGradientBrush Class 296
The RadialGradientBrush Class 299
The ImageBrush 301
Transparency 302
Opacity Masks 305
Making the Silverlight Control Transparent 306
Transforms 310
Transforming Shapes 312
Transforms and Layout Containers 314
A Reflection Effect 315
Perspective Transforms 317
The PlaneProjection Class 318
Applying a Projection 320
Pixel Shaders 321
BlurEffect 322
DropShadowEffect 322
ShaderEffect 324
The WriteableBitmap Class 325
Generating a Bitmap 325
Capturing Content from Other Elements 328
Printing 329
Printing a Single Element 330
Printing Over Multiple Pages 332
Creating a Print Preview 335
The Last Word 338

www.it-ebooks.info
■ CONTENTS
xiii
■ Chapter 10: Animation 339
Understanding Silverlight Animation 339

The Rules of Animation 340
Creating Simple Animations 341
The Animation Class 341
The Storyboard Class 342
Starting an Animation with an Event Trigger 343
Starting an Animation with Code 344
Configuring Animation Properties 345
Animation Lifetime 347
Simultaneous Animations 350
Controlling Playback 350
Animation Easing 353
Using an Easing Function 353
Easing In and Easing Out 354
Easing Function Classes 356
Animation Types Revisited 359
Animating Transforms 359
Animation Perspective Projections 362
Animating Brushes 364
Animating Pixel Shaders 365
Key-Frame Animation 367
Animations in Code 371
The Main Page 372
The Bomb User Control 374
Dropping the Bombs 375

Intercepting a Bomb 379
Counting Bombs and Cleaning Up 380
Encapsulating Animations 382
Page Transitions 382
The Base Class 384
The Wipe Transition 385
Frame-Based Animation 387
www.it-ebooks.info
■ CONTENTS

xiv
Animation Performance 391
Desired Frame Rate 391
Hardware Acceleration 392
The Last Word 397
■ Chapter 11: Sound, Video, and Deep Zoom 399
Supported File Types 399

The MediaElement 400
Controlling Playback 401
Handling Errors 402
Playing Multiple Sounds 402
Changing Volume, Balance, and Position 403
Playing Video 407
Client-Side Playlists 408
Server-Side Playlists 408
Progressive Downloading and Streaming 409
Adaptive Streaming 411
Advanced Video Playback 412
Video Encoding 412

Encoding in Expression Encoder 413
Markers 415
VideoBrush 420
Video Effects 421
Webcam and Microphone Input 427
Accessing a Capture Device 427
Basic Webcam Support 429
Recording Audio Snippets 432
Deep Zoom 436
Creating a Deep Zoom Image Set 438
Using a Deep Zoom Image Set in Silverlight 442
The Last Word 445
■ Chapter 12: Styles and Behaviors 447
Styles 447

Defining a Style 448
Applying a Style 449
www.it-ebooks.info
■ CONTENTS
xv
Dynamic Styles 450
Style Inheritance 450
Organizing Styles 452
Automatically Applying Styles by Type 452
Behaviors 454
Getting Support for Behaviors 454
Triggers and Actions 455
Creating a Behavior 465
Finding More Behaviors 468
The Last Word 470

■ Chapter 13: Templates and Custom Controls 471
Template Basics 471

Creating a Template 472
Reusing Control Templates 473
The ContentPresenter 474
Template Bindings 475
Setting Templates Through Styles 476
Reusing Colors 478
The Parts and States Model 478
Understanding States with the Button Control 480
Showing a Focus Cue 484
Transitions 485
Understanding Parts with the Slider Control 490
Creating Templates for Custom Controls 494
Planning the FlipPanel Control 495
Creating the Solution 496
Starting the FlipPanel Class 496
Adding the Default Style with Generic.xaml 498
Choosing Parts and States 500
Starting the Default Control Template 502
The FlipButton Control 503
Defining the State Animations 504
Wiring Up the Elements in the Template 506
Using the FlipPanel 508
www.it-ebooks.info
■ CONTENTS

xvi
Using a Different Control Template 509

The Last Word 511
■ Chapter 14: Browser Integration 513
Interacting with HTML Elements 514

Getting Browser Information 515
The HTML Window 516
Popup Windows 517
Inspecting the HTML Document 518
Manipulating an HTML Element 520
Handling JavaScript Events 525
Code Interaction 527
Calling Browser Script from Silverlight 528
Calling Silverlight Methods from the Browser 528
Instantiating Silverlight Objects in the Browser 530
Combining Silverlight and HTML Content 532
Sizing the Silverlight Control to Fit Its Content 532
Placing the Silverlight Control Next to an HTML Element 534
Securing HTML Interoperability 536
The Last Word 538
■ Chapter 15: ASP.NET Web Services 539
Building Web Services for Silverlight 539

Creating a Web Service 539
Adding a Service Reference 541
Calling the Web Service 543
Configuring the Web Service URL 546
Using a Busy Indicator 547
Web Service Data Types 549
Custom Data Classes 549
Web Service Type Sharing 551

More Advanced Web Services 556
Cross-Domain Web Service Calls 556
Monitoring the Network Connection 558
Using ASP.NET Platform Services 560
www.it-ebooks.info
■ CONTENTS
xvii
Duplex Services 562
Configuring the Service 562
The Interfaces 563
The Service 565
The Client 565
The Last Word 567
■ Chapter 16: Data Binding 569
Binding to Data Objects 569

Building a Data Object 570
Displaying a Data Object with DataContext 571
Storing a Data Object as a Resource 573
Null Values and Failed Bindings 574
Editing with Two-Way Bindings 574
Change Notification 576
Building a Data Service 577
Calling a Data Service 581
Binding to a Collection of Objects 583
Displaying and Editing Collection Items 583
Inserting and Removing Collection Items 588
Binding to a LINQ Expression 588
Master-Details Display 591
Validation 594

Error Notifications 595
The BindingValidationFailed Event 597
The Validation Class 599
Creating Data Objects with Built-in Validation 599
Data Formatting and Conversion 603
String Formatting 604
Value Converters 606
Formatting Strings with a Value Converter 606
Creating Objects with a Value Converter 609
Applying Conditional Formatting 611
Data Templates 613
Separating and Reusing Templates 615
www.it-ebooks.info
■ CONTENTS

xviii
More Advanced Templates 616
Changing Item Layout 617
The Last Word 618
■ Chapter 17: Data Controls 619
Better Data Forms 620
The Goal: Data Class Markup 620
The Label 621
The DescriptionViewer 623
The ValidationSummary 625
Data Annotations 627
Raising Annotation Errors 628
The Annotation Attributes 629
The DataGrid 635
Creating a Simple Grid 636

How Columns Are Resized and Rearranged 638
Defining Columns 639
Formatting and Styling Columns 642
Controlling Column Width 644
Formatting Rows 646
Row Details 649
Freezing Columns 650
Selection 651
Sorting 652
DataGrid Editing 653
Editing with Templates 653
Validation and Editing Events 655
The PagedCollectionView 657
Sorting 658
Filtering 658
Grouping 659
Paging 662
The TreeView 665
Filling a TreeView 665
A Data-Bound TreeView 665
The Last Word 668
www.it-ebooks.info
■ CONTENTS
xix
■ Chapter 18: File Access 669
Isolated Storage 670

The Scope of Isolated Storage 670
What to Put in Isolated Storage 671
Using Isolated Storage 671

Opening an Isolated Store 671
File Management 672
Writing and Reading Data 673
Requesting More Space 675
Storing Objects with XmlSerializer 677
Storing Application Settings 680
Accessing Files Outside of Isolated Storage 681
Reading Files with OpenFileDialog 682
Writing Files with SaveFileDialog 684
Transmitting Files with a Web Service 684
Dragging and Dropping Files 690
The Last Word 694
■ Chapter 19: Multithreading 695
Understanding Multithreading 695

The Goals of Multithreading 696
The DispatcherTimer 697
The Thread Class 697
Marshaling Code to the User Interface Thread 699
Creating a Thread Wrapper 702
Creating the Worker Class 703
Using the Thread Wrapper 705
Cancellation Support 707
The BackgroundWorker 708
Creating the BackgroundWorker 709
Running the BackgroundWorker 710
Tracking Progress 712
Supporting Cancellation 714
The Last Word 716
www.it-ebooks.info

■ CONTENTS
xx
■ Chapter 20: Networking 717
Interacting with the Web 718
Cross-Domain Access. 718
HTML Scraping . 720
REST and Other Simple Web Services 725
Using Network Credentials 729
Processing Different Types of Data 729
XML . 729
Services That Return XML Data 730
Services That Require XML Data 737
Services That Return SOAP Data 740
Services That Return JSON Data 740
RSS. 743
Sockets . 746
Understanding Sockets and TCP 746
The Policy Server. 748
The Messaging Server 753
The Messenger Client . 757
Local Connections . 762
Sending a Message. 763
Receiving a Message . 764
The Last Word . 765
■ Chapter 21: Out-of-Browser Applications 767
Understanding Out-of-Browser Support 768
Creating an Out-of-Browser Application 769
Installing an Out-of-Browser Application 771
Customizing Icons . 774
Tracking Application State 775

Removing and Updating an Application 779
Silent Installation . 780
Out-of-Browser Application Features 781
The WebBrowser Control 781
Notification Windows 785
Controlling the Main Window 788
www.it-ebooks.info
■ CONTENTS
xxi
Elevated Trust 790
Installing an Elevated Trust Application 791
The Abilities of an Elevated Trust Application 794
Window Customization 795
File Access 802
COM 804
The Last Word 808

■ Index 809


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# 2010,
Pro ASP.NET 4 in C# 2010, and Beginning ASP.NET in C# 2010. He’s also the author of Your
Brain: The Missing Manual (Pogue Press, 2008), a popular look at getting the most from your
squishy gray matter. Matthew lives in Toronto with his wife and two daughters.

www.it-ebooks.info
■ CONTENTS
xxiii
About the Technical Reviewer
■ Fabio Claudio Ferracchiati is a prolific writer on cutting-edge technologies. Fabio has
contributed to more than a dozen books on .NET, C#, Visual Basic, and ASP.NET. He is a .NET
Microsoft Certified Solution Developer (MCSD) and lives in Rome, Italy.

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
×