“Essential Silverlight 3 is not only filled with technical details, clear examples, and performance tips that will make any Silverlight application better, butAshraf also includes insigh
Trang 1ptg
Trang 2“Essential Silverlight 3 is not only filled with technical details, clear examples,
and performance tips that will make any Silverlight application better, butAshraf also includes insights that can only come from one of the lead devel-opers of the Silverlight runtime From graphics, to text, to media—this bookcontains all the information you need on the core Silverlight 3 runtime.”
—Brad Abrams, product unit manager, Microsoft
“The third iteration of Silverlight is a big step forward in true line-of-businesscapability for RIAs Ashraf takes these new concepts and puts them forth
in a meaningful and concise read.”
—Jason Beres, Microsoft MVP; author; INETA Speaker
“Essential Silverlight 3 is truly an essential book in the library of any
Silverlight developer The ‘Under the Hood’ portions of each chapterexplain the details of Silverlight’s implementation, and the ‘PerformanceTips’ explain how to use that information to get the most out of your soft-ware I am very grateful I don’t have to track down or figure out all of thiscritical information on my own.”
—Noah Gedrich, director of technology, BLITZ Agency
“Ashraf Michail delivers an insightful and practical book for anyone seeking
to better understand, master, and unlock the full potential of Silverlight 3
It is filled with code samples, performance tips, and other useful advice tohelp you create truly outstanding Silverlight applications.”
—Oleg Kokorin, CEO, MS Team, LLC
“Essential Silverlight 3 tackles in depth a rich, vast platform The author has
a depth of knowledge and technical insight that is present throughout, providing a pleasing ‘why’ on top of the usual ‘how.’”
—Richard Leggett, interactive developer
“This is a book of inestimable value on Silverlight Even experienced
Silverlight developers will learn from Essential Silverlight 3.”
—Mark Monster, software engineer, Rubicon
Trang 3“A great reference and textbook on Silverlight 3.”
—Judith Myerson, systems architect and engineer
“Chock full of performance tips and information about Silverlight internalsthat you won’t find anywhere else.”
—Jeff Prosise, cofounder, Wintellect
“Skillfully written, comprehensively explained, and logically delivered
Essential Silverlight 3 is undoubtedly a must-have study and
keep-on-your-desk practical guide for building a wide range of high-value richInternet applications.”
—Ash Rofail, CEO, Santeon, Inc.
“Essential Silverlight 3 is a must-read for anyone who wants a better
understanding of the Silverlight Framework In his book, Ashraf Michail,architect on the Silverlight team, offers unique insights into Silverlight’sarchitecture and design principles, along with guidance on how toimprove the overall quality and performance of Silverlight applications.”
—Gerhard Schneider, senior development lead, Microsoft
“Essential Silverlight 3 does not just get your feet wet—its technical insights
and performance tips take you for a deep dive into the Silverlight ocean.”
—Velvárt András, Silverlight MVP; founder, Response Ltd
“This book really lives up to the title—Essential, indeed Anyone
doing Silverlight 3, or looking to get started with it, needs this book close at hand.”
—Chris G Williams, Microsoft MVP and principal consultant,
Magenic Technologies
“A must-read for all software developers who are trying to build rich Silverlight applications with great performance—it provides many usefulperformance tips I would recommend it to anyone trying to improve performance of Silverlight 3 applications.”
—Radenko Zec, senior software developer, Lanaco; INETA group leader,
Banjaluka, Bosnia and Herzegovina
Trang 4Essential Silverlight 3
Trang 5The award-winning Microsoft NET Development Series was
established in 2002 to provide professional developers with the most comprehensive, practical coverage of the latest NET technologies
Authors in this series include Microsoft architects, MVPs, and other experts and leaders in the field of Microsoft development technologies
Each book provides developers with the vital information and critical insight they need to write highly effective applications
Visit informit.com /msdotnetseries for a complete list of available products.
NET Development Series
Trang 6ptgAshraf Michail
Essential Silverlight 3
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
Trang 7Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The NET logo is either a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries and is used under license from Microsoft.
Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries/regions.
The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact:
U.S Corporate and Government Sales (800) 382-3419
corpsales@pearsontechgroup.com For sales outside the United States, please contact:
International Sales international@pearson.com Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data
Michail, Ashraf.
Essential Silverlight 3 / Ashraf Michail.
p cm.
Includes index.
ISBN 978-0-321-55416-1 (pbk : alk paper) 1 Silverlight (Electronic resource) 2 Multimedia systems
3 Websites—Design 4 Application software—Development
I Title.
QA76.575.M52187 2009 2009 006.7—dc22
2009026788 Copyright © 2010 Pearson Education, Inc.
All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
501 Boylston Street, Suite 900 Boston, MA 02116
Fax: (617) 671-3447 ISBN-13: 978-0-321-55416-1 ISBN-10: 0-321-55416-7 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
Trang 8ptg
Trang 9This page intentionally left blank
Trang 10Contents
Figures xvii Foreword xxiii Preface xxv Acknowledgments xxix About the Author xxxi
1 Silverlight Overview 1
Silverlight Principles 3
Web Deployment 3 Security 3
Media and Rich Internet Applications 4 Ease of Development 5
Cross Platform 5
Silverlight Features 6
Application Model 7 Graphics 7
Text 7 Input 8 Animation 8 Layout 8 Media 8 Controls 9 Data Binding 9
Trang 11Event System 37 Animation 37 Layout 38 Rendering 39
Where Are We? 39
Trang 12Graphics Elements 48
Shapes 48 Images 61 Brushes 62 Image Brushes 68 Strokes 69 Canvas 72
Under the Hood 81
Draw Loop 82 Rasterization 82 Bilinear Filtering 89 Incremental Redraw 92 Occlusion Culling 94 Multi-Core Rendering 94 How Content Gets to the Screen 95
Where Are We? 96
4 Text 97
Text Principles 98
Cross-Platform Consistency 98 Scale Independent Layout 98 Rendering for Readability 99
Text Elements 99
TextBlock 100 Glyphs 107
Under the Hood 110
Font Enumeration 110 Font Fallback 111 Font Download 111 Caches 112 Rasterization 112
Where Are We? 113
5 Input Events 115
Input Principles 115
Receiving Web Browser Events 116
Trang 13Contents
Custom Controls 117 Cross-Platform Consistency 117 Multiple Languages 118
Where Are We? 130
Animation Elements 136
Starting an Animation 138 Interpolation and Key Frame Animations 140 Timelines 144
Easing Functions (New in Silverlight 3) 144 Custom Animation Functions (New in Silverlight 3) 147
Under the Hood 147
The Animation Tick 148 Property Change Speed 149 Screen Display 151
Where Are We? 152
7 Layout 153
Layout Principles 153
Automatic Sizing and Positioning 154 Automatic Application Resize 156 Scale Independent Layout 157
Layout Elements 158
xii
Trang 14Canvas 158 Border 159 StackPanel 161 Grid 162 Layout Rounding 167 Building a Custom Layout 169 Layout Events 173
Under the Hood 174
The Layout Algorithm 174
Where Are We? 176
8 Media 177
Media Principles 178
Integrate Media 178 Deliver Content 178 Deliver Full Screen Experiences 179 Generate Players with Expression Media Encoder 180
Media Elements 180
Play a Video 180 Making Player Controls 183 Video Effects and Transitions 187 Full Screen 188
Connecting Video Markers to Application Display 189
Under the Hood 190
The Source 190 The Player 191
Where Are We? 193
9 Controls 195
Control Principles 196
Built-In Controls 196 Custom Controls 198 Customization 198
Control Elements 198
ContentControl and ItemsControl 199 VisualStateManager 203
Trang 15Contents
Styling 206 Create Custom Controls 207
Under the Hood 209
Control Instantiation 209 The Visual State Manager Algorithm 210
Where Are We? 211
10 Data Binding 213
Data Binding Principles 213
Data Sources 214 Automatic Connection and Synchronization 214 Declarative XAML Model 214
Data Binding Objects 215
Connecting to Data with a Binding 215 DataContext Inheritance 218
Data Synchronization and Binding Modes 219 Data Binding Collections with ItemsControl 221 Value Converters 225
Data Validation 227 Element to Element Binding (New in Silverlight 3) 228
Under the Hood 229
Binding Object 229 ItemsControl 230
Where Are We? 231
11 Effects 233
Effect Principles 233
Real-Time Speed 233 Common Built-In Effects 234
Effect Elements 234
Applying an Effect 234 Creating an Effect 236
Under the Hood 248
Surface Generation 248 BlurEffect and DropShadowEffect 249
Where Are We? 250
xiv
Trang 1612 GPU Acceleration 251
GPU Acceleration Principles 251
Achieve Better Performance for Common Scenarios 252 Maintain Good Image Quality 252
Maintain Reasonable Stability 252
GPU Acceleration Features 253
GPU Acceleration Prerequisites 253 Enable GPU Acceleration 253 Using the CacheMode Property 254 Diagnose Performance Problems 259
Under the Hood 263
Graphics Device Creation 263 Texture Creation 264
Rendering Stages with GPU Acceleration Enabled 265 Multiple Monitors 265
Where Are We? 265
Index 267
Trang 17This page intentionally left blank
Trang 18Figures
F IGURE 1.1: Example Silverlight sites shown at http://silverlight.net/showcase 2
F IGURE 1.2: Installing a Silverlight application so that it can run outside the Web
browser 2
F IGURE 1.3: Visiting a Silverlight Web page without installing the Silverlight
runtime 4
F IGURE 2.1: Visual Studio Silverlight application project 14
F IGURE 2.2: Hello World application 16
F IGURE 2.3: Application install menu 22
F IGURE 2.4: Application install prompt 22
F IGURE 2.5: Application running outside the Web browser 23
F IGURE 2.6: Example path 25
F IGURE 2.7: Architectural Overview 33
F IGURE 2.8: Layout Example 38
F IGURE 3.1: Scaling up an image of a circle 42
F IGURE 3.2: Scaling down an image of a circle 42
F IGURE 3.3: Scaling a vector graphic circle 42
F IGURE 3.4: Removing a rectangle with a retained mode API 44
F IGURE 3.5: Removing a rectangle with an immediate mode API 44
F IGURE 3.6: Rectangle element with an outline 49
F IGURE 3.7: Rectangle element with rounded corners 50
F IGURE 3.8: Ellipse element 51
Trang 19F IGURE 3.9: Line element 52
F IGURE 3.10: Pixels rendered for a Line element 53
F IGURE 3.11: Sharp horizontal line drawn with a Rectangle element 54
F IGURE 3.12: Example path 55
F IGURE 3.13: Path with an empty space in the center 58
F IGURE 3.14: Different fills for the same outline 59
F IGURE 3.15: Winding mode numbers resulting in a filled center space 60
F IGURE 3.16: Different fill as a result of a different point order 61
F IGURE 3.17: Image element example 62
F IGURE 3.18: Linear gradient brush 65
F IGURE 3.19: Radial gradient brush 66
F IGURE 3.20: Focal gradient brush 67
F IGURE 3.21: SpreadMethod example 68
F IGURE 3.22: ImageBrush example 68
F IGURE 3.23: Sample stroke applied to an ellipse 69
F IGURE 3.24: The widening process applied to an ellipse 70
F IGURE 3.25: The widening process applied to a triangle 71
F IGURE 3.26: StrokeDashArray example of long and short dashes 71
F IGURE 3.27: RenderTransform example of overlapping a rectangle over
an ellipse 73
F IGURE 3.28: 3D projection example 75
F IGURE 3.29: Position three rectangles in the same 3D projection camera 76
F IGURE 3.30: Clipping example 78
F IGURE 3.31: Canvas Opacity versus per path Opacity 79
F IGURE 3.32: OpacityMask example 80
F IGURE 3.33: Sampling a circle 84
F IGURE 3.34: Sampling a circle with integer sample point coordinates 85
F IGURE 3.35: Anti-aliasing sampling pattern 85
F IGURE 3.36: Anti-aliased rasterization 86
F IGURE 3.37: Anti-aliasing seam example 87
F IGURE 3.38: Pixel snapped rasterization 88
F IGURE 3.39: Seams with a rotated edge 89
F IGURE 3.40: Image with bilinear filtering 90
F IGURE 3.41: Image with nearest neighbor 90
Figure s
xviii
Trang 20F IGURE 3.42: The bilinear filtering process 91
F IGURE 3.43: Image scaling within good limits 91
F IGURE 3.44: Image scaling extremes 92
F IGURE 3.45: Incremental redraw regions 93
F IGURE 3.46: Dividing a scene for multi-core rendering 95
F IGURE 4.1: TextBlock example 100
F IGURE 4.2: TextBlock wrapping example 100
F IGURE 4.3: TextBlock border with ActualWidth and ActualHeight 101
F IGURE 4.4: TextBlock alignment example 103
F IGURE 4.5: TextBlock formatting example 104
F IGURE 4.6: Inherited formatting 104
F IGURE 4.7: Text radial gradient example 105
F IGURE 4.8: Math formula using Glyphs element 109
F IGURE 4.9: Text baseline 110
F IGURE 5.1: Hit-test area for a Canvas with a rectangle and circle 125
F IGURE 6.1: Frame-based animation 132
F IGURE 6.2: Time-based animation 133
F IGURE 6.3: Animation timing artifacts 135
F IGURE 6.4: Smooth spline versus linear segment interpolation 141
F IGURE 6.5: Bounce animation 145
F IGURE 6.6: Easing out functions 146
F IGURE 7.1: Surrounding text with a rounded rectangle 154
F IGURE 7.2: Positioning elements in a vertical stack 155
F IGURE 7.3: Automatic resize behavior 157
F IGURE 7.4: Positioning content explicitly with the Canvas element 158
F IGURE 7.5: Surrounding a TextBlock element with a border 160
F IGURE 7.6: Adding a rounded rectangle background to a TextBlock element 160
F IGURE 7.7: Padding a border element 160
F IGURE 7.8: Vertical StackPanel example 161
F IGURE 7.9: Horizontal StackPanel example 161
Trang 21F IGURE 7.10: Grid example 162
F IGURE 7.11: ColumnSpan example 163
F IGURE 7.12: Grid as the root element 164
F IGURE 7.13: Grid example with Auto and * row and column definitions 164
F IGURE 7.14: Grid example 2* row and column definitions 165
F IGURE 7.15: HorizontalAlignment and VerticalAlignment example 166
F IGURE 7.16: Anti-aliasing seam example 167
F IGURE 7.17: Pixel snapped rasterization 168
F IGURE 7.18: WrapPanel example 169
F IGURE 8.1: MediaElement example 181
F IGURE 8.2: Media with player controls 183
F IGURE 8.3: Media with player controls with a status indicator 185
F IGURE 8.4: Cory Newton-Smith’s video puzzle example 187
F IGURE 9.1: Sample Silverlight built-in controls 196
F IGURE 9.2: Example Silverlight toolkit controls 197
F IGURE 9.3: Theming a bar graph control 198
F IGURE 9.4: Using a ContentControl element 199
F IGURE 9.5: Using a ContentControl 3D template 200
F IGURE 9.6: ItemsControl sample 201
F IGURE 9.7: Simple customized button 204
F IGURE 9.8: Using a style 207
F IGURE 10.1: Data binding a data record to a TextBox 215
F IGURE 10.2: Data binding to a list 222
F IGURE 10.3: Data binding to a ComboBox 223
F IGURE 10.4: Element to element binding 229
F IGURE 11.1: Drop shadow effect applied to text 234
F IGURE 11.2: Blur effect applied to text 235
F IGURE 11.3: Red pixel effect applied to an ellipse producing a square 238
F IGURE 11.4: Correct red pixel effect applied to an ellipse 240
F IGURE 11.5: A mask effect 243
Figure s
xx
Trang 22F IGURE 11.6: Debug pixel shader 245
F IGURE 11.7: Opacity parameter passed to a pixel shader 246
F IGURE 11.8: Adjusting the elementPosition parameter before sampling
the input 247
F IGURE 12.1: Example layers generated by CacheMode property 256
F IGURE 12.2: Final frame of zoom animation 257
F IGURE 12.3: Final frame of zoom animation with RenderAtScale 259
F IGURE 12.4: Framerate display 260
F IGURE 12.5: Colored surface indicating an implicit surface 261
F IGURE 12.6: Optimized circle animation with less memory usage 262
Trang 23This page intentionally left blank
Trang 24Foreword
SILVERLIGHT IS Across-browser, cross-platform plugin that enables developers
to build rich media and RIA Web experiences It allows developers to use.NET within the browser to create scenarios that can’t be achieved using anyother Web technology, and to use high productivity tools like Visual Studioand Expression Studio when doing so
The new Silverlight 3 release delivers more than 200 new features fordevelopers to leverage, including the ability to run Silverlight applications in
or out of the browser; stream HD and H.264 video; display 3D graphics anduse GPU acceleration; take advantage of richer data-binding support; use newbitmap APIs and animation easing capabilities; and much, much more
Ashraf Michail, the author of the book you are holding in your hands,
is one of the star developers of the Silverlight team He has been involved
in the architecture since we first began working on it and brought to theeffort his deep experience with and understanding of Silverlight’s “bigbrother,” the Windows Presentation Foundation Ashraf knows intimatelythe ins and outs of the Silverlight runtime, and in this book he has distilledhis understanding into a clear, concise exposition
This isn’t the only book on Silverlight 3, by any means: I’m happy to saythat several other good Silverlight 3 books are in the works However, this isthe only book that focuses on the Silverlight runtime and gives you an in-depth understanding of how it works Once you know what’s really hap-pening in the runtime engine, you’ll be in a position to take full advantage ofSilverlight’s speed and power Look for the “Under the Hood” section at theend of each chapter of this book: You won’t find that anywhere else
Trang 25Also look for the “Technical Insight,” “Debugging Tip,” and “PerformanceTip” sections scattered throughout the book These are the nuggets that youcan take away and use to make your own applications fly Is too much dataslowing down your ComboBox display? You can filter your Items Source tospeed that up, as explained in Chapter 10 Would your application benefitfrom GPU acceleration? Chapter 12 shows you how to make that happen,explains the four stages of the GPU acceleration pipeline—and explains thetradeoffs involved in GPU acceleration on each supported operating system
so that you can understand why turning on GPU acceleration might notalways help
The book you are holding contains the keys to writing great Silverlight 3applications Use them well!
—Scott Guthrie, corporate vice president, Microsoft Developer Division
Foreword
xxiv