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

pro silverlight 4 in vb, 3rd edition

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 (16.17 MB, 897 trang )

MacDonald
Silverlight 4 in VB
Companion
eBook Available
7.5 x 9.25 spine = 1.6875" 896 page count
THE EXPERT’S VOICE
®
IN SILVERLIGHT
Pro
Silverlight 4
in VB

Matthew MacDonald
Create cross-platform .NET applications
for the browser
CYAN
MAGENTA
YELLOW
BLACK
PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Pro Silverlight 4 in VB
Silverlight is a revolutionary browser plug-in that allows developers to create rich
client applications that run inside the browser. Like Adobe Flash, Silverlight sup-
ports event handling, two-dimensional drawing, video playback, networking, and
animation. Unlike Flash, Silverlight is tailored to .NET developers and supports
pure Visual Basic code.
The most exciting part of Silverlight is its cross-platform muscle. Unlike ordi-
nary .NET applications, Silverlight applications run seamlessly in non-Microsoft
browsers (such as Firefox, Safari, and Chrome) and on non-Microsoft platforms


(such as Mac OS X). Essentially, Silverlight is a scaled-down, browser-hosted ver-
sion of .NET—and that’s made it the most hotly anticipated technology that
Microsoft has released in years.
In this book, you’ll master Silverlight from the ground up. No Silverlight expe-
rience is required—but if you’ve worked with Silverlight 3, you’ll appreciate 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 complete Silverlight
platform, and you’ll be able to build anything from a slick business front end to a
browser-based game.
Matthew MacDonald,
author of
Pro WPF in VB 2010
Pro ASP.NET 4 in VB 2010
(with Adam Freeman and
Mario Szpuszta)
Beginning ASP.NET 4 in VB
2010
Your Brain: The Missing
Manual
Shelve in:
.NET
User level:
Intermediate–Advanced
THE APRESS ROADMAP
Pro
Windows Phone 7
Development
Pro
Business Applications
with Silverlight 4

Pro
Silverlight 4 in VB
Pro
WPF in VB 2010
Introducing
Silverlight 4
Beginning
ASP.NET in VB 2010
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-3548-4
9 781430 235484
55999
Pro
THIRD EDITION
THIRD EDITION
www.it-ebooks.info
www.it-ebooks.info


Pro Silverlight 4 in VB
Third Edition















■ ■ ■
Matthew MacDonald



www.it-ebooks.info
Pro Silverlight 4 in VB, Third Edition
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 owner and the
publisher.
ISBN-13 (pbk): 978-1-4302-3548-4
ISBN-13 (electronic): 978-1-4302-3549-1
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.
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham

Technical Reviewer: Fabio Claudio Ferracchiati
Editorial Board: 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-Verlag New York, Inc., 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.
The source code for this book is available to readers at www.apress.com. You will need to answer
questions pertaining to this book in order to successfully download the code.
www.it-ebooks.info
For my family

www.it-ebooks.info
www.it-ebooks.info

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 225
■ Chapter 8: Shapes and Geometries 257
■ Chapter 9: Brushes, Transforms, and Bitmaps 293
■ Chapter 10: Animation 335
■ Chapter 11: Sound, Video, and Deep Zoom 391
■ Chapter 12: Styles and Behaviors 439
■ Chapter 13: Templates and Custom Controls 463
■ Chapter 14: Browser Integration 503
■ Chapter 15: ASP.NET Web Services 529
■ Chapter 16: Data Binding 559
■ Chapter 17: Data Controls 609
■ Chapter 18: File Access 657
■ Chapter 19: Multithreading 683
■ C
hapter 20: Networking 705

■ Chapter 21: Out-of-Browser Applications 753

■ Index 793

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 34
The Code-Behind Class 38
Properties and Events in XAML 39
Simple Properties and Type Converters 40
Complex Properties 42
Attached Properties 44
Nesting Elements 45
Events 48
The Full Eight Ball Example 48
XAML Resources 49
The Resources Collection 50
The Hierarchy of Resources 51
Accessing Resources in Code 53
Organizing Resources with Resource Dictionaries 54
Element-to-Element Binding 55
One-Way Binding 55
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 126
Mouse Cursors 130
www.it-ebooks.info
■ CONTENTS
ix
Keyboard Handling 131
Key Presses 131
Key Modifiers 133
Focus 134

The Command Model 135
Building a Command 136
Connecting a Command 137
The Last Word 139
■ 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. 190
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 . 203
Unhandled Exceptions. 203
Custom Splash Screens. 206
Binary Resources . 210
Placing Resources in the Application Assembly 210
Placing Resources in the Application Package 213
Placing Resources on the Web 214
Class Library Assemblies. 218
Using Resources in an Assembly 218

Downloading Assemblies on Demand 219
Supporting Assembly Caching . 220
The Last Word. 224
■ Chapter 7: Navigation . 225
Loading User Controls . 226
Embedding User Controls in a Page 226
Hiding Elements . 228
Download from Wow! eBook <www.wowebook.com>
www.it-ebooks.info
■ CONTENTS
xi
Managing the Root Visual 228
Retaining Page State 230
Browser History 231
Child Windows 231
Designing a ChildWindow 233
Showing a ChildWindow 234
The Frame and Page 236
Frames 236
URI Mapping 243
Forward and Backward Navigation 244
Hyperlinks 245
Pages 246
Navigation Templates 249
Custom Content Loaders 250
Authentication and Navigation 251
Creating a Custom Content Loader 252
Using the Custom Content Loader 254
The Last Word 255
■ Chapter 8: Shapes and Geometries 257

Basic Shapes 257

The Shape Classes 258
Rectangle and Ellipse 259
Sizing and Placing Shapes 261
Sizing Shapes Proportionately with a Viewbox 263
Line 265
Polyline 266
Polygon 267
Line Caps and Line Joins 270
Dashes 272
Paths and Geometries 274
Line, Rectangle, and Ellipse Geometries 275
Combining Shapes with GeometryGroup 276
Curves and Lines with PathGeometry 278
www.it-ebooks.info
■ CONTENTS

xii
The Geometry Mini-Language 283
Clipping with Geometry 285
Exporting Clip Art 287
Expression Design 287
Conversion 288
Save or Print to XPS 289
The Last Word 291
■ Chapter 9: Brushes, Transforms, and Bitmaps 293
Brushes 293

The LinearGradientBrush Class 294

The RadialGradientBrush Class 297
The ImageBrush 299
Transparency 300
Opacity Masks 302
Making the Silverlight Control Transparent 304
Transforms 308
Transforming Shapes 310
Transforms and Layout Containers 312
A Reflection Effect 313
Perspective Transforms 314
The PlaneProjection Class 315
Applying a Projection 317
Pixel Shaders 318
BlurEffect 319
DropShadowEffect 319
ShaderEffect 321
The WriteableBitmap Class 322
Generating a Bitmap 322
Capturing Content from Other Elements 325
Printing 326
Printing a Single Element 327
Printing Over Multiple Pages 329
Creating a Print Preview 332
The Last Word 334
www.it-ebooks.info
■ CONTENTS
xiii
■ Chapter 10: Animation 335
Understanding Silverlight Animation 335


The Rules of Animation 336
Creating Simple Animations 337
The Animation Class 337
The Storyboard Class 338
Starting an Animation with an Event Trigger 339
Starting an Animation with Code 339
Configuring Animation Properties 340
Animation Lifetime 343
Simultaneous Animations 345
Controlling Playback 346
Animation Easing 348
Using an Easing Function 349
Easing In and Easing Out 350
Easing Function Classes 351
Animation Types Revisited 354
Animating Transforms 354
Animation Perspective Projections 357
Animating Brushes 358
Animating Pixel Shaders 360
Key-Frame Animation 361
Animations in Code 365
The Main Page 366
The Bomb User Control 368
Dropping the Bombs 369
Intercepting a Bomb 372
Counting Bombs and Cleaning Up 374
Encapsulating Animations 376
Page Transitions 376
The Base Class 377
The Wipe Transition 378

Frame-Based Animation 380
www.it-ebooks.info
■ CONTENTS

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

The MediaElement 392
Controlling Playback 393
Handling Errors 394
Playing Multiple Sounds 394
Changing Volume, Balance, and Position 395
Playing Video 399
Client-Side Playlists 399
Server-Side Playlists 400
Progressive Downloading and Streaming 400
Adaptive Streaming 402
Advanced Video Playback 403
Video Encoding 403
Encoding in Expression Encoder 404
Markers 406
VideoBrush 411
Video Effects 412
Webcam and Microphone Input 418
Accessing a Capture Device 418

Basic Webcam Support 420
Recording Audio Snippets 423
Deep Zoom 427
Creating a Deep Zoom Image Set 429
Using a Deep Zoom Image Set in Silverlight 433
The Last Word 437
■ Chapter 12: Styles and Behaviors 439
Styles 439

Defining a Style 440
www.it-ebooks.info
■ CONTENTS
xv
Applying a Style 441
Dynamic Styles 442
Style Inheritance 442
Organizing Styles 444
Automatically Applying Styles by Type 444
Behaviors 445
Getting Support for Behaviors 446
Triggers and Actions 447
Creating a Behavior 457
Finding More Behaviors 460
The Last Word 462
■ Chapter 13: Templates and Custom Controls 463
Template Basics 463

Creating a Template 464
Reusing Control Templates 465
The ContentPresenter 466

Template Bindings 467
Setting Templates Through Styles 468
Reusing Colors 470
The Parts and States Model 470
Understanding States with the Button Control 472
Showing a Focus Cue 476
Transitions 477
Understanding Parts with the Slider Control 482
Creating Templates for Custom Controls 486
Planning the FlipPanel Control 487
Creating the Solution 487
Starting the FlipPanel Class 488
Adding the Default Style with Generic.xaml 489
Choosing Parts and States 491
Starting the Default Control Template 493
The FlipButton Control 494
Defining the State Animations 495
Wiring Up the Elements in the Template 497
www.it-ebooks.info
■ CONTENTS

xvi
Using the FlipPanel 499
Using a Different Control Template 500
The Last Word 502
■ Chapter 14: Browser Integration 503
Interacting with HTML Elements 504

Getting Browser Information 505
The HTML Window 506

Popup Windows 507
Inspecting the HTML Document 508
Manipulating an HTML Element 510
Handling JavaScript Events 515
Code Interaction 517
Calling Browser Script from Silverlight 518
Calling Silverlight Methods from the Browser 518
Instantiating Silverlight Objects in the Browser 520
Combining Silverlight and HTML Content 522
Sizing the Silverlight Control to Fit Its Content 522
Placing the Silverlight Control Next to an HTML Element 523
Securing HTML Interoperability 526
The Last Word 527
■ Chapter 15: ASP.NET Web Services 529
Building Web Services for Silverlight 529

Creating a Web Service 529
Adding a Service Reference 531
Calling the Web Service 533
Configuring the Web Service URL 536
Using a Busy Indicator 537
Web Service Data Types 539
Custom Data Classes 539
Web Service Type Sharing 540
More Advanced Web Services 545
Cross-Domain Web Service Calls 546
Monitoring the Network Connection 548
Using ASP.NET Platform Services 549
www.it-ebooks.info
■ CONTENTS

xvii
Duplex Services 551
Configuring the Service 551
The Interfaces 552
The Service 554
The Client 555
The Last Word 557
■ Chapter 16: Data Binding 559
Binding to Data Objects 559

Building a Data Object 560
Displaying a Data Object with DataContext 561
Storing a Data Object as a Resource 563
Null Values and Failed Bindings 564
Editing with Two-Way Bindings 564
Change Notification 566
Building a Data Service 567
Calling a Data Service 571
Binding to a Collection of Objects 572
Displaying and Editing Collection Items 573
Inserting and Removing Collection Items 576
Binding to a LINQ Expression 577
Master-Details Display 579
Validation 583
Error Notifications 583
The BindingValidationFailed Event 586
The Validation Class 587
Creating Data Objects with Built-in Validation 588
Data Formatting and Conversion 592
String Formatting 592

Value Converters 594
Formatting Strings with a Value Converter 595
Creating Objects with a Value Converter 597
Applying Conditional Formatting 599
Data Templates 602
Separating and Reusing Templates 604
www.it-ebooks.info
■ CONTENTS

xviii
More Advanced Templates 604
Changing Item Layout 606
The Last Word 607
■ Chapter 17: Data Controls 609
Better Data Forms 610

The Goal: Data Class Markup 610
The Label 611
The DescriptionViewer 613
The ValidationSummary 615
Data Annotations 617
Raising Annotation Errors 618
The Annotation Attributes 619
The DataGrid 625
Creating a Simple Grid 626
How Columns Are Resized and Rearranged 628
Defining Columns 629
Formatting and Styling Columns 632
Controlling Column Width 634
Formatting Rows 636

Row Details 638
Freezing Columns 639
Selection 640
Sorting 641
DataGrid Editing 642
Editing with Templates 642
Validation and Editing Events 643
The PagedCollectionView 646
Sorting 647
Filtering 647
Grouping 648
Paging 650
The TreeView 653
Filling a TreeView 653
A Data-Bound TreeView 653
The Last Word 656
www.it-ebooks.info
■ CONTENTS
xix
■ Chapter 18: File Access 657
Isolated Storage 658

The Scope of Isolated Storage 658
What to Put in Isolated Storage 659
Using Isolated Storage 659
Opening an Isolated Store 659
File Management 660
Writing and Reading Data 661
Requesting More Space 663
Storing Objects with XmlSerializer 665

Storing Application Settings 668
Accessing Files Outside of Isolated Storage 669
Reading Files with OpenFileDialog 670
Writing Files with SaveFileDialog 672
Transmitting Files with a Web Service 672
Dragging and Dropping Files 678
The Last Word 681
■ Chapter 19: Multithreading 683
Understanding Multithreading 683

The Goals of Multithreading 684
The DispatcherTimer 685
The Thread Class 685
Marshaling Code to the User Interface Thread 687
Creating a Thread Wrapper 689
Creating the Worker Class 691
Using the Thread Wrapper 692
Cancellation Support 694
The BackgroundWorker 696
Creating the BackgroundWorker 696
Running the BackgroundWorker 697
Tracking Progress 700
Supporting Cancellation 702
The Last Word 704
www.it-ebooks.info
■ CONTENTS
xx
■ Chapter 20: Networking . 705
Interacting with the Web . 706
Cross-Domain Access . 706

HTML Scraping. 708
REST and Other Simple Web Services 712
Using Network Credentials. 717
Processing Different Types of Data 717
XML 717
Services That Return XML Data . 718
Services That Require XML Data 725
Services That Return SOAP Data 727
Services That Return JSON Data 728
RSS 731
Sockets 733
Understanding Sockets and TCP . 734
The Policy Server . 736
The Messaging Server . 740
The Messenger Client. 744
Local Connections. 749
Sending a Message . 750
Receiving a Message. 751
The Last Word. 752
■ Chapter 21: Out-of-Browser Applications 753
Understanding Out-of-Browser Support 754
Creating an Out-of-Browser Application 755
Installing an Out-of-Browser Application 757
Customizing Icons. 760
Tracking Application State . 761
Removing and Updating an Application 764
Silent Installation . 766
Out-of-Browser Application Features 766
The WebBrowser Control . 767
Notification Windows . 770

Controlling the Main Window 773
Download from Wow! eBook <www.wowebook.com>
www.it-ebooks.info
■ CONTENTS
xxi
Elevated Trust 775
Installing an Elevated Trust Application 775
The Abilities of an Elevated Trust Application 778
Window Customization 779
File Access 786
COM 788
The Last Word 792

■ Index 793


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 VB 2010, Pro ASP.NET 4 in C# 2010,
and Beginning ASP.NET in VB 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

×