🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

wpf-4-unleashed.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

Adam Nathan WPF 4 UNLEASHED 800 East 96th Street, Indianapolis, Indiana 46240 USA WPF 4 Unleashed Editor-in-Chief Copyright © 2010 by Pearson Education...

Adam Nathan WPF 4 UNLEASHED 800 East 96th Street, Indianapolis, Indiana 46240 USA WPF 4 Unleashed Editor-in-Chief Copyright © 2010 by Pearson Education Karen Gettman All rights reserved. No part of this book shall be reproduced, stored in a retrieval Executive Editor system, or transmitted by any means, electronic, mechanical, photocopying, recording, Neil Rowe or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every Development Editor precaution has been taken in the preparation of this book, the publisher and author Mark Renfrow assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. Managing Editor ISBN-13: 978-0-672-33119-0 Kristy Hart ISBN-10: 0-672-33119-5 Project Editor Library of Congress Cataloging-in-Publication Data Betsy Harris Nathan, Adam. WPF 4 unleashed / Adam Nathan. Copy Editor p. cm. Kitty Wilson Includes index. ISBN 978-0-672-33119-0 Indexer 1. Windows presentation foundation. 2. Application software. 3. Microsoft.NET Erika Millen Framework. I. Title. Proofreader QA76.76.A65N386 2010 006.7’882—dc22 Kathy Ruiz 2010017765 Technical Editors Printed in the United States on America Dwayne Need First Printing June 2010 Robert Hogue Joe Castro Trademarks Jordan Parker All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of Publishing Coordinator this information. Use of a term in this book should not be regarded as affecting the Cindy Teeters validity of any trademark or service mark. Book Designer Warning and Disclaimer Gary Adair Every effort has been made to make this book as complete and as accurate as possi- ble, but no warranty or fitness is implied. The information provided is on an “as is” Composition basis. The author(s) and the publisher shall have neither liability nor responsibility to Bronkella Publishing LLC any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it. Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside of the U.S., please contact International Sales [email protected] From the Library of Wow! eBook Contents at a Glance Introduction................................................................................................................................................... 1 Part I Background 1 Why WPF, and What About Silverlight?................................................................................. 9 2 XAML Demystified................................................................................................................................. 21 3 WPF Fundamentals............................................................................................................................... 73 Part II Building a WPF Application 4 Sizing, Positioning, and Transforming Elements........................................................... 97 5 Layout with Panels.............................................................................................................................. 115 6 Input Events: Keyboard, Mouse, Stylus, and Multi-Touch.................................. 159 7 Structuring and Deploying an Application...................................................................... 195 8 Exploiting Windows 7...................................................................................................................... 233 Part III Controls 9 Content Controls................................................................................................................................. 261 10 Items Controls........................................................................................................................................ 275 11 Images, Text, and Other Controls........................................................................................... 309 Part IV Features for Professional Developers 12 Resources..................................................................................................................................................... 343 13 Data Binding............................................................................................................................................ 363 14 Styles, Templates, Skins, and Themes.................................................................................. 415 Part V Rich Media 15 2D Graphics.............................................................................................................................................. 475 16 3D Graphics.............................................................................................................................................. 537 17 Animation................................................................................................................................................. 607 18 Audio, Video, and Speech............................................................................................................. 653 Part VI Advanced Topics 19 Interoperability with Non-WPF Technologies............................................................... 675 20 User Controls and Custom Controls.................................................................................... 721 21 Layout with Custom Panels........................................................................................................ 751 Index.............................................................................................................................................................. 775 From the Library of Wow! eBook Table of Contents Introduction 1 Who Should Read This Book?.......................................................................................................... 2 Software Requirements.......................................................................................................................... 3 Code Examples.............................................................................................................................................. 4 How This Book Is Organized............................................................................................................. 4 Part I: Background........................................................................................................................ 4 Part II: Building a WPF Application............................................................................... 4 Part III: Controls............................................................................................................................ 5 Part IV: Features for Professional Developers......................................................... 5 Part V: Rich Media...................................................................................................................... 5 Part VI: Advanced Topics........................................................................................................ 6 Conventions Used in This Book.................................................................................................... 6 Part I Background 1 Why WPF, and What About Silverlight? 9 A Look at the Past................................................................................................................................... 10 Enter WPF..................................................................................................................................................... 11 The Evolution of WPF.......................................................................................................................... 14 Enhancements in WPF 3.5 and WPF 3.5 SP1...................................................... 15 Enhancements in WPF 4.................................................................................................... 16 What About Silverlight?..................................................................................................................... 18 Summary......................................................................................................................................................... 19 2 XAML Demystified 21 XAML Defined.......................................................................................................................................... 23 Elements and Attributes..................................................................................................................... 24 Namespaces................................................................................................................................................. 26 Property Elements................................................................................................................................... 29 Type Converters........................................................................................................................................ 30 Markup Extensions................................................................................................................................. 32 Children of Object Elements.......................................................................................................... 35 The Content Property............................................................................................................ 35 Collection Items.......................................................................................................................... 36 More Type Conversion.......................................................................................................... 38 From the Library of Wow! eBook Mixing XAML with Procedural Code...................................................................................... 40 Loading and Parsing XAML at Runtime.................................................................. 40 Compiling XAML...................................................................................................................... 43 Introducing XAML2009..................................................................................................................... 48 Full Generics Support............................................................................................................. 49 Dictionary Keys of Any Type........................................................................................... 50 Built-In System Data Types............................................................................................... 50 Instantiating Objects with Non-Default Constructors................................ 51 Getting Instances via Factory Methods.................................................................... 51 Event Handler Flexibility.................................................................................................... 52 Defining New Properties...................................................................................................... 53 Fun with XAML Readers and Writers...................................................................................... 53 Overview.......................................................................................................................................... 53 The Node Loop............................................................................................................................ 56 Reading XAML.............................................................................................................................. 57 Writing to Live Objects........................................................................................................ 61 Writing to XML.......................................................................................................................... 63 XamlServices................................................................................................................................. 64 XAML Keywords....................................................................................................................................... 67 Summary......................................................................................................................................................... 70 Complaint 1: XML Is Too Verbose to Type........................................................... 71 Complaint 2: XML-Based Systems Have Poor Performance................... 71 3 WPF Fundamentals 73 A Tour of the Class Hierarchy........................................................................................................ 73 Logical and Visual Trees..................................................................................................................... 75 Dependency Properties...................................................................................................................... 80 A Dependency Property Implementation............................................................... 81 Change Notification............................................................................................................... 83 Property Value Inheritance................................................................................................. 85 Support for Multiple Providers........................................................................................ 87 Attached Properties................................................................................................................... 89 Summary......................................................................................................................................................... 93 Part II Building a WPF Application 4 Sizing, Positioning, and Transforming Elements 97 Controlling Size........................................................................................................................................ 98 Height and Width..................................................................................................................... 98 Margin and Padding............................................................................................................. 100 Visibility........................................................................................................................................ 102 From the Library of Wow! eBook vi WPF 4 Unleashed Controlling Position.......................................................................................................................... 103 Alignment..................................................................................................................................... 103 Content Alignment............................................................................................................... 104 FlowDirection............................................................................................................................ 105 Applying Transforms.......................................................................................................................... 106 RotateTransform...................................................................................................................... 108 ScaleTransform.......................................................................................................................... 109 SkewTransform.......................................................................................................................... 112 TranslateTransform............................................................................................................... 112 MatrixTransform..................................................................................................................... 112 Combining Transforms...................................................................................................... 113 Summary..................................................................................................................................................... 114 5 Layout with Panels 115 Canvas.......................................................................................................................................................... 116 StackPanel................................................................................................................................................... 118 WrapPanel................................................................................................................................................. 120 DockPanel................................................................................................................................................... 122 Grid.................................................................................................................................................................. 125 Sizing the Rows and Columns...................................................................................... 130 Interactive Sizing with GridSplitter......................................................................... 132 Sharing Row and Column Sizes.................................................................................. 134 Comparing Grid to Other Panels............................................................................... 136 Primitive Panels..................................................................................................................................... 137 TabPanel........................................................................................................................................ 137 ToolBarPanel............................................................................................................................... 138 ToolBarOverflowPanel........................................................................................................ 138 ToolBarTray................................................................................................................................. 138 UniformGrid............................................................................................................................... 138 SelectiveScrollingGrid.......................................................................................................... 138 Handling Content Overflow........................................................................................................ 139 Clipping.......................................................................................................................................... 139 Scrolling.......................................................................................................................................... 141 Scaling.............................................................................................................................................. 143 Putting It All Together: Creating a Visual Studio–Like Collapsible, Dockable, Resizable Pane............................................................................................................ 147 Summary..................................................................................................................................................... 157 From the Library of Wow! eBook Contents vii 6 Input Events: Keyboard, Mouse, Stylus, and Multi-Touch 159 Routed Events.......................................................................................................................................... 159 A Routed Event Implementation............................................................................... 160 Routing Strategies and Event Handlers................................................................ 161 Routed Events in Action................................................................................................... 162 Attached Events...................................................................................................................... 165 Keyboard Events..................................................................................................................................... 168 Mouse Events.......................................................................................................................................... 170 MouseEventArgs...................................................................................................................... 171 Drag and Drop.......................................................................................................................... 172 Capturing the Mouse.......................................................................................................... 173 Stylus Events............................................................................................................................................ 174 StylusDevice............................................................................................................................... 174 Events.............................................................................................................................................. 175 Multi-Touch Events.............................................................................................................................. 176 Basic Touch Events................................................................................................................. 177 Manipulation Events for Panning, Rotating, and Zooming.................. 180 Commands................................................................................................................................................ 188 Built-In Commands............................................................................................................. 189 Executing Commands with Input Gestures...................................................... 192 Controls with Built-In Command Bindings...................................................... 193 Summary..................................................................................................................................................... 194 7 Structuring and Deploying an Application 195 Standard Windows Applications............................................................................................... 195 The Window Class................................................................................................................. 196 The Application Class.......................................................................................................... 199 Showing a Splash Screen................................................................................................... 205 Creating and Showing Dialogs.................................................................................... 206 Persisting and Restoring Application State......................................................... 209 Deployment: ClickOnce Versus Windows Installer..................................... 210 Navigation-Based Windows Applications......................................................................... 211 Pages and Their Navigation Containers............................................................... 212 Navigating from Page to Page...................................................................................... 214 Passing Data Between Pages........................................................................................... 219 Gadget-Style Applications............................................................................................................. 223 XAML Browser Applications........................................................................................................ 224 Limited Feature Set............................................................................................................... 226 Integrated Navigation.......................................................................................................... 228 Deployment............................................................................................................................... 229 Loose XAML Pages............................................................................................................................... 231 Summary..................................................................................................................................................... 232 From the Library of Wow! eBook viii WPF 4 Unleashed 8 Exploiting Windows 7 233 Jump Lists................................................................................................................................................... 233 JumpTask....................................................................................................................................... 234 JumpPath....................................................................................................................................... 241 Taskbar Item Customizations...................................................................................................... 245 Using a Taskbar Item Progress Bar............................................................................. 246 Adding an Overlay to the Taskbar Item............................................................... 247 Customizing the Thumbnail Content.................................................................... 247 Adding Thumb Buttons to the Taskbar Thumbnail.................................... 248 Aero Glass................................................................................................................................................... 249 TaskDialog................................................................................................................................................. 253 Summary..................................................................................................................................................... 256 Part III Controls 9 Content Controls 261 Buttons.......................................................................................................................................................... 263 Button.............................................................................................................................................. 264 RepeatButton.............................................................................................................................. 265 ToggleButton.............................................................................................................................. 265 CheckBox....................................................................................................................................... 266 RadioButton............................................................................................................................... 266 Simple Containers............................................................................................................................... 268 Label................................................................................................................................................. 268 ToolTip............................................................................................................................................ 269 Frame................................................................................................................................................ 271 Containers with Headers............................................................................................................... 272 GroupBox....................................................................................................................................... 273 Expander........................................................................................................................................ 273 Summary..................................................................................................................................................... 274 10 Items Controls 275 Common Functionality................................................................................................................... 276 DisplayMemberPath............................................................................................................. 277 ItemsPanel..................................................................................................................................... 278 Controlling Scrolling Behavior.................................................................................... 280 Selectors....................................................................................................................................................... 281 ComboBox................................................................................................................................... 282 ListBox............................................................................................................................................ 287 ListView.......................................................................................................................................... 290 From the Library of Wow! eBook Contents ix TabControl................................................................................................................................... 291 DataGrid........................................................................................................................................ 292 Menus............................................................................................................................................................ 298 Menu................................................................................................................................................ 298 ContextMenu............................................................................................................................ 301 Other Items Controls........................................................................................................................ 302 TreeView........................................................................................................................................ 302 ToolBar............................................................................................................................................ 304 StatusBar........................................................................................................................................ 307 Summary..................................................................................................................................................... 308 11 Images, Text, and Other Controls 309 The Image Control.............................................................................................................................. 309 Text and Ink Controls...................................................................................................................... 311 TextBlock....................................................................................................................................... 313 TextBox.......................................................................................................................................... 315 RichTextBox............................................................................................................................... 316 PasswordBox............................................................................................................................... 316 InkCanvas..................................................................................................................................... 316 Documents................................................................................................................................................. 318 Creating Flow Documents............................................................................................... 318 Displaying Flow Documents.......................................................................................... 329 Adding Annotations............................................................................................................. 331 Range Controls....................................................................................................................................... 334 ProgressBar................................................................................................................................... 335 Slider................................................................................................................................................. 335 Calendar Controls............................................................................................................................... 336 Calendar........................................................................................................................................ 336 DatePicker..................................................................................................................................... 338 Summary..................................................................................................................................................... 339 Part IV Features for Professional Developers 12 Resources 343 Binary Resources................................................................................................................................... 343 Defining Binary Resources............................................................................................... 344 Accessing Binary Resources............................................................................................. 345 Localizing Binary Resources........................................................................................... 350 Logical Resources................................................................................................................................... 351 Resource Lookup..................................................................................................................... 355 Static Versus Dynamic Resources............................................................................... 355 Interaction with System Resources........................................................................... 360 Summary..................................................................................................................................................... 362 From the Library of Wow! eBook x WPF 4 Unleashed 13 Data Binding 363 Introducing the Binding Object............................................................................................... 363 Using Binding in Procedural Code........................................................................... 363 Using Binding in XAML.................................................................................................... 365 Binding to Plain.NET Properties............................................................................... 367 Binding to an Entire Object........................................................................................... 369 Binding to a Collection...................................................................................................... 370 Sharing the Source with DataContext.................................................................... 374 Controlling Rendering..................................................................................................................... 375 String Formatting................................................................................................................... 375 Using Data Templates.......................................................................................................... 378 Using Value Converters.................................................................................................... 381 Customizing the View of a Collection................................................................................. 386 Sorting.............................................................................................................................................. 386 Grouping....................................................................................................................................... 388 Filtering.......................................................................................................................................... 392 Navigating..................................................................................................................................... 392 Working with Additional Views.................................................................................. 394 Data Providers........................................................................................................................................ 396 XmlDataProvider..................................................................................................................... 397 ObjectDataProvider............................................................................................................... 401 Advanced Topics................................................................................................................................... 403 Customizing the Data Flow........................................................................................... 403 Adding Validation Rules to Binding........................................................................ 405 Working with Disjoint Sources.................................................................................... 409 Putting It All Together: The Pure-XAML Twitter Client......................................... 412 Summary..................................................................................................................................................... 414 14 Styles, Templates, Skins, and Themes 415 Styles.............................................................................................................................................................. 416 Sharing Styles............................................................................................................................ 418 Triggers............................................................................................................................................ 423 Templates..................................................................................................................................................... 430 Introducing Control Templates.................................................................................. 431 Getting Interactivity with Triggers........................................................................... 432 Restricting the Target Type............................................................................................. 434 Respecting the Templated Parent’s Properties.................................................. 435 Respecting Visual States with Triggers.................................................................... 442 Respecting Visual States with the Visual State Manager (VSM)......... 447 Mixing Templates with Styles...................................................................................... 456 Skins................................................................................................................................................................ 458 From the Library of Wow! eBook Contents xi Themes.......................................................................................................................................................... 465 Using System Colors, Fonts, and Parameters.................................................... 465 Per-Theme Styles and Templates................................................................................. 466 Summary..................................................................................................................................................... 470 Part V Rich Media 15 2D Graphics 475 Drawings..................................................................................................................................................... 476 Geometries................................................................................................................................... 479 Pens................................................................................................................................................... 489 Clip Art Example..................................................................................................................... 491 Visuals............................................................................................................................................................ 493 Filling a DrawingVisual with Content.................................................................. 493 Displaying a Visual on the Screen............................................................................. 496 Visual Hit Testing................................................................................................................... 499 Shapes............................................................................................................................................................ 505 Rectangle....................................................................................................................................... 507 Ellipse................................................................................................................................................ 508 Line................................................................................................................................................... 509 Polyline.......................................................................................................................................... 510 Polygon.......................................................................................................................................... 511 Path................................................................................................................................................... 511 Clip Art Based on Shapes................................................................................................. 512 Brushes.......................................................................................................................................................... 513 Color Brushes............................................................................................................................ 513 Tile Brushes................................................................................................................................. 520 Brushes as Opacity Masks................................................................................................. 527 Effects............................................................................................................................................................ 529 Improving Rendering Performance........................................................................................ 532 RenderTargetBitmap............................................................................................................. 532 BitmapCache.............................................................................................................................. 533 BitmapCacheBrush............................................................................................................... 535 Summary..................................................................................................................................................... 535 16 3D Graphics 537 Getting Started with 3D Graphics........................................................................................... 538 Cameras and Coordinate Systems........................................................................................... 542 Position.......................................................................................................................................... 543 LookDirection............................................................................................................................ 544 UpDirection................................................................................................................................. 548 OrthographicCamera Versus PerspectiveCamera........................................... 551 From the Library of Wow! eBook xii WPF 4 Unleashed Transform3D............................................................................................................................................ 554 TranslateTransform3D........................................................................................................ 556 ScaleTransform3D................................................................................................................... 557 RotateTransform3D............................................................................................................... 559 Combining Transform3Ds............................................................................................... 562 Model3D....................................................................................................................................................... 563 Lights................................................................................................................................................ 563 GeometryModel3D............................................................................................................... 571 Model3DGroup........................................................................................................................ 584 Visual3D....................................................................................................................................................... 586 ModelVisual3D.......................................................................................................................... 587 UIElement3D.............................................................................................................................. 588 Viewport2DVisual3D............................................................................................................ 590 3D Hit Testing............................................................................................................................ 592 Viewport3D................................................................................................................................................ 593 2D and 3D Coordinate System Transformation........................................................... 596 Visual.TransformToAncestor.......................................................................................... 596 Visual3D.TransformToAncestor and Visual3D.TransformToDescendant........................................................................ 600 Summary..................................................................................................................................................... 605 17 Animation 607 Animations in Procedural Code............................................................................................... 608 Performing Animation “By Hand”........................................................................... 608 Introducing the Animation Classes......................................................................... 609 Simple Animation Tweaks............................................................................................... 616 Animations in XAML........................................................................................................................ 621 EventTriggers Containing Storyboards.................................................................. 621 Using Storyboard as a Timeline.................................................................................. 629 Keyframe Animations........................................................................................................................ 630 Linear Keyframes..................................................................................................................... 631 Spline Keyframes..................................................................................................................... 633 Discrete Keyframes................................................................................................................. 634 Easing Keyframes..................................................................................................................... 636 Easing Functions................................................................................................................................... 637 Built-In Power Easing Functions................................................................................. 637 Other Built-In Easing Functions................................................................................. 639 Writing Your Own Easing Function......................................................................... 640 Animations and the Visual State Manager........................................................................ 643 Transitions................................................................................................................................... 647 Summary..................................................................................................................................................... 651 From the Library of Wow! eBook Contents xiii 18 Audio, Video, and Speech 653 Audio.............................................................................................................................................................. 653 SoundPlayer................................................................................................................................. 654 SoundPlayerAction................................................................................................................. 654 MediaPlayer................................................................................................................................. 655 MediaElement and MediaTimeline........................................................................... 656 Video.............................................................................................................................................................. 658 Controlling the Visual Aspects of MediaElement......................................... 658 Controlling the Underlying Media........................................................................... 661 Speech............................................................................................................................................................ 664 Speech Synthesis..................................................................................................................... 664 Speech Recognition............................................................................................................... 667 Summary..................................................................................................................................................... 672 Part VI Advanced Topics 19 Interoperability with Non-WPF Technologies 675 Embedding Win32 Controls in WPF Applications.................................................... 677 A Win32 Webcam Control............................................................................................. 678 Using the Webcam Control in WPF........................................................................ 681 Supporting Keyboard Navigation............................................................................... 687 Embedding WPF Controls in Win32 Applications.................................................... 692 Introducing HwndSource................................................................................................. 692 Getting the Right Layout................................................................................................. 696 Embedding Windows Forms Controls in WPF Applications............................ 699 Embedding a PropertyGrid with Procedural Code....................................... 700 Embedding a PropertyGrid with XAML............................................................... 702 Embedding WPF Controls in Windows Forms Applications............................ 704 Mixing DirectX Content with WPF Content................................................................ 708 Embedding ActiveX Controls in WPF Applications.................................................. 714 Summary..................................................................................................................................................... 718 20 User Controls and Custom Controls 721 Creating a User Control................................................................................................................... 723 Creating the User Interface of the User Control........................................... 723 Creating the Behavior of the User Control....................................................... 725 Adding Dependency Properties to the User Control.................................. 728 Adding Routed Events to the User Control....................................................... 731 From the Library of Wow! eBook xiv WPF 4 Unleashed Creating a Custom Control.......................................................................................................... 732 Creating the Behavior of the Custom Control.............................................. 733 Creating the User Interface of the Custom Control.................................... 739 Considerations for More Sophisticated Controls........................................... 743 Summary..................................................................................................................................................... 750 21 Layout with Custom Panels 751 Communication Between Parents and Children......................................................... 752 The Measure Step................................................................................................................... 752 The Arrange Step..................................................................................................................... 754 Creating a SimpleCanvas............................................................................................................... 755 Creating a SimpleStackPanel........................................................................................................ 760 Creating an OverlapPanel............................................................................................................. 763 Creating a FanCanvas...................................................................................................................... 768 Summary..................................................................................................................................................... 773 Index 775 From the Library of Wow! eBook About the Author Adam Nathan is a principal software development engineer for Microsoft Visual Studio, the latest version of which has been transformed into a first-class WPF application. Adam was previously the founding developer and architect for Popfly, Microsoft’s first product built on Silverlight, named one of the 25 most innovative products of 2007 by PCWorld Magazine. Having started his career on Microsoft’s Common Language Runtime team, Adam has been at the core of.NET and WPF technologies since the very beginning. Adam’s books have been considered required reading by many inside Microsoft and throughout the industry. He is the author of the best-selling WPF Unleashed (Sams, 2006) that was nominated for a 2008 Jolt Award, Silverlight 1.0 Unleashed (Sams, 2008), and.NET and COM: The Complete Interoperability Guide (Sams, 2002); a coauthor of ASP.NET: Tips, Tutorials, and Code (Sams, 2001); and a contributor to books including.NET Framework Standard Library Annotated Reference, Volume 2 (Addison-Wesley, 2005) and Windows Developer Power Tools (O’Reilly, 2006). Adam is also the creator of PINVOKE.NET and its Visual Studio add-in. You can find him online at www.adamnathan.net, or @adamnathan on Twitter. From the Library of Wow! eBook Dedication To Lindsay, Tyler, and Ryan. Acknowledgments As always, I’d like to thank my wonderful wife, Lindsay, for her incredible support and understanding. Our life is always heavily affected by the seemingly never-ending process of writing a book, and by now you think she would have run out of patience. However, she has never been more supportive than she has been for this book. Lindsay, I couldn’t have done it without you. Although most of the process of writing a book is very solitary, this book came together because of the work of many talented and hard-working people. I’d like to take a moment to thank some of them by name. I’d like to sincerely thank Dwayne Need, senior development manager from the WPF team, for being a fantastic technical editor. His feedback on my drafts was so thorough and insightful, the book is far better because of him. I’d like to thank Robert Hogue, Joe Castro, and Jordan Parker for their helpful reviews. David Teitlebaum, 3D expert from the WPF team, deserves many thanks for agreeing to update the great 3D chapter originally written by Daniel Lehenbauer. Having Daniel’s and David’s perspectives and advice captured on paper is a huge benefit for any readers thinking about dabbling in 3D. I’d also like to thank (in alphabetical order): Brian Chapman, Beatriz de Oliveira Costa, Ifeanyi Echeruo, Dan Glick, Neil Kronlage, Rico Mariani, Mike Mueller, Oleg Ovetchkine, Lori Pearce, S. Ramini, Rob Relyea, Tim Rice, Ben Ronco, Adam Smith, Tim Sneath, David Treadwell, and Paramesh Vaidyanathan. I’d like to thank the folks at Sams—especially Neil Rowe and Betsy Harris, who are always a pleasure to work with. I couldn’t have asked for a better publishing team. Never once was I told that my content was too long or too short or too different from a typical Unleashed title. They gave me the complete freedom to write the kind of book I wanted to write. I’d like to thank my mom, dad, and brother for opening my eyes to the world of computer programming when I was in elementary school. If you have children, please expose them to the magic of writing software while they’re still young enough to care about what you have to say! (WPF and Silverlight can even help you make the experience fun!) Finally, I thank you for picking up a copy of this book and reading at least this far! I hope you continue reading and find the journey of exploring WPF 4 as fascinating as I have! From the Library of Wow! eBook We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what 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 what you did or didn’t like about this book—as well as what 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 phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book. E-mail: [email protected] Mail: Neil Rowe Executive Editor Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA Reader Services Visit our website and register this book at informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book. From the Library of Wow! eBook This page intentionally left blank From the Library of Wow! eBook Introduction Thank you for picking up WPF 4 Unleashed! Windows Presentation Foundation (WPF) is Microsoft’s premier technology for creating Windows graphical user interfaces, whether they consist of plain forms, document-centric windows, animated cartoons, videos, immersive 3D environments, or all of the above. WPF is a technology that makes it easier than ever to create a broad range of applications. It’s also the basis for Silverlight, which has extended WPF technology onto the Web and into devices such as Windows phones. Ever since WPF was publicly announced in 2003 (with the code name “Avalon”), it has gotten considerable attention for the ways in which it revolutionizes the process of creat- ing software—especially for Windows programmers used to Windows Forms and GDI. It’s relatively easy to create fun, useful, and shareable WPF samples that demonstrate all kinds of techniques that are difficult to accomplish in other technologies. WPF 4, released in April 2010, improves on previous versions of WPF in just about every dimension. WPF is quite a departure from previous technologies in terms of its programming model, underlying concepts, and basic terminology. Even viewing the source code for WPF (by cracking open its components with a tool such as.NET Reflector) is a confusing experi- ence because the code you’re looking for often doesn’t reside where you’d expect to find it. When you combine all this with the fact that there are often several ways to accom- plish any task in WPF, you arrive at a conclusion shared by many: WPF has a very steep learning curve. That’s where this book comes in. As WPF was developed, it was obvious that there would be no shortage of WPF books in the marketplace. But it wasn’t clear to me that the books would have the right balance to guide people through the technology and its unique concepts while showing practical ways to exploit it. Therefore, I wrote the first edition of this book, Windows Presentation Foundation Unleashed, with the following goals in mind:. To provide a solid grounding in the underlying concepts, in a practical and approachable fashion. To answer the questions most people have when learning the technology and to show how commonly desired tasks are accomplished. To be an authoritative source, thanks to input from members of the WPF team who designed, implemented, and tested the technology. To be clear about where the technology falls short rather than selling the technol- ogy as the answer to all problems. To be an easily navigated reference that you can constantly come back to The first edition of this book was far more successful than I ever imagined it would be. Now, almost four years later, I believe that this second edition accomplishes all the same From the Library of Wow! eBook 2 WPF 4 Unleashed goals but with even more depth. In addition to covering new features introduced in WPF 3.5, WPF 3.5 SP1, and WPF 4, it expands the coverage of the existing features from the first version of WPF. Whether you’re new to WPF or a long-time WPF developer, I hope you find this book to exhibit all these attributes. Who Should Read This Book? This book is for software developers who are interested in creating user interfaces for Windows. Regardless of whether you’re creating line-of-business applications, consumer- facing applications, or reusable controls, this book contains a lot of content that helps you get the most out of the platform. It’s designed to be understandable even for folks who are new to the.NET Framework. And if you are already well versed in WPF, I’m confident that this book still has information for you. At the very least, it should be an invaluable reference for your bookshelf. Because the technology and concepts behind WPF are the same ones behind Silverlight, reading this book can also make you a better developer for Windows Phone 7 and even a better web developer. Although this book’s content is not optimized for graphic designers, reading this book can be a great way to understand more of the “guts” behind a product like Microsoft Expression Blend. To summarize, this book does the following:. Covers everything you need to know about Extensible Application Markup Language (XAML), the XML-based language for creating declarative user interfaces that can be easily restyled. Examines the WPF feature areas in incredible depth: controls, layout, resources, data binding, styling, graphics, animation, and more. Highlights the latest features, such as multi-touch, text rendering improvements, new controls, XAML language enhancements, the Visual State Manager, easing func- tions, and much more. Delves into topics that aren’t covered by most books: 3D, speech, audio/video, docu- ments, effects, and more. Shows how to create popular user interface elements, such as galleries, ScreenTips, custom control layouts, and more. Demonstrates how to create sophisticated user interface mechanisms, such as Visual Studio–like collapsible/dockable panes. Explains how to develop and deploy all types of applications, including navigation- based applications, applications hosted in a web browser, and applications with great-looking nonrectangular windows. Explains how to create first-class custom controls for WPF From the Library of Wow! eBook Introduction 3. Demonstrates how to create hybrid WPF software that leverages Windows Forms, DirectX, ActiveX, or other non-WPF technologies. Explains how to exploit new Windows 7 features in WPF applications, such as Jump Lists, and how to go beyond some of the limitations of WPF This book doesn’t cover every last bit of WPF. (In particular, XML Paper Specification [XPS] documents are given only a small bit of attention.) WPF’s surface area is so large that I don’t believe any single book can. But I think you’ll be pleased with the breadth and depth achieved by this book. Examples in this book appear in XAML and C#, plus C++/CLI for interoperability discus- sions. XAML is used heavily for a number of reasons: It’s often the most concise way to express source code, it can often be pasted into lightweight tools to see instant results without any compilation, WPF-based tools generate XAML rather than procedural code, and XAML is applicable no matter what.NET language you use, such as Visual Basic instead of C#. Whenever the mapping between XAML and a language such as C# is not obvious, examples are shown in both representations. Software Requirements This book targets the final release of version 4.0 of Windows Presentation Foundation, the corresponding Windows SDK, and Visual Studio 2010. The following software is required:. A version of Windows that supports the.NET Framework 4.0. This can be Windows XP with Service Pack 2 (including Media Center, Tablet PC, and x64 editions), Windows Server 2003 with Service Pack 1 (including the R2 edition), Windows Vista, or later versions.. The.NET Framework 4.0, which is installed by default starting with Windows Vista. For earlier versions of Windows, you can download the.NET Framework 4.0 for free from http://msdn.com. In addition, the following software is recommended:. The Windows Software Development Kit (SDK), specifically the.NET tools it includes. This is also a free download from http://msdn.com.. Visual Studio 2010 or later, which can be a free Express edition downloaded from http://msdn.com. If you want additional tool support for WPF-based graphic design, Microsoft Expression (specifically Expression Blend) can be extremely helpful. A few examples are specific to Windows Vista, Windows 7, or a computer that supports multi-touch, but the rest of the book applies equally to all relevant versions of Windows. From the Library of Wow! eBook 4 WPF 4 Unleashed Code Examples The source code for examples in this book can be downloaded from http://informit.com/ title/9780672331190 or http://adamnathan.net/wpf. How This Book Is Organized This book is arranged into six main parts, representing the progression of feature areas that you typically need to understand to use WPF effectively. But if you’re dying to jump ahead and learn about a topic such as 3D or animation, the book is set up to allow for nonlinear journeys as well. The following sections provide a summary of each part. Part I: Background This part includes the following chapters:. Chapter 1: Why WPF, and What About Silverlight?. Chapter 2: XAML Demystified. Chapter 3: WPF Fundamentals Chapter 1 introduces WPF by comparing it to alternative technologies and helping you make decisions about when WPF is appropriate for your needs. Chapter 2 explores XAML in great depth, giving you the foundation to understand the XAML you’ll encounter in the rest of the book and in real life. Chapter 3 highlights the most unique pieces of WPF’s programming model above and beyond what.NET programmers already understand. Part II: Building a WPF Application This part includes the following chapters:. Chapter 4: Sizing, Positioning, and Transforming Elements. Chapter 5: Layout with Panels. Chapter 6: Input Events: Keyboard, Mouse, Stylus, and Multi-Touch. Chapter 7: Structuring and Deploying an Application. Chapter 8: Exploiting Windows 7 Part II equips you with the knowledge to assemble and deploy a traditional-looking appli- cation (although some fancier effects, such as transforms, nonrectangular windows, and Aero Glass, are also covered). Chapters 4 and 5 discuss arranging controls (and other elements) in a user interface. Chapter 6 covers input events, including new support for engaging multi-touch user interfaces. Chapter 7 examines several different ways to package and deploy WPF-based user interfaces to make complete applications. Chapter 8 ends this part by showing slick ways to exploit features in Windows 7 that can help make your application look modern. From the Library of Wow! eBook Introduction 5 Part III: Controls This part includes the following chapters:. Chapter 9: Content Controls. Chapter 10: Items Controls. Chapter 11: Images, Text, and Other Controls Part III provides a tour of controls built into WPF. There are many that you’d expect to have available, plus several that you might not expect. Two categories of controls— content controls (Chapter 9) and items controls (Chapter 10)—are important and deep enough topics to merit their own chapters. The rest of the controls are examined in Chapter 11. Part IV: Features for Professional Developers This part includes the following chapters:. Chapter 12: Resources. Chapter 13: Data Binding. Chapter 14: Styles, Templates, Skins, and Themes The features covered in Part IV are not always necessary to use in WPF applications, but they can greatly enhance the development process. Therefore, they are indispensable for professional developers who are serious about creating maintainable and robust applica- tions or components. These topics are less about the results visible to end users than they are about the best practices for accomplishing these results. Part V: Rich Media This part includes the following chapters:. Chapter 15: 2D Graphics. Chapter 16: 3D Graphics. Chapter 17: Animation. Chapter 18: Audio, Video, and Speech This part of the book covers the features in WPF that typically get the most attention. The support for 2D and 3D graphics, animation, video, and more enable you to create a stun- ning experience. These features—and the way they are exposed—set WPF apart from previous systems. WPF lowers the barrier to incorporating such content in your software, so you might try some of these features that you never would have dared to try in the past! From the Library of Wow! eBook 6 WPF 4 Unleashed Part VI: Advanced Topics This part includes the following chapters:. Chapter 19: Interoperability with Non-WPF Technologies. Chapter 20: User Controls and Custom Controls. Chapter 21: Layout with Custom Panels The topics covered in Part VI are relevant for advanced application developers, or devel- opers of WPF-based controls. The fact that existing WPF controls can be radically restyled greatly reduces the need for creating custom controls. Conventions Used in This Book Various typefaces in this book identify new terms and other special items. These typefaces include the following: Typeface Meaning Italic Italic is used for new terms or phrases when they are initially defined and occa- sionally for emphasis. Monospace Monospace is used for screen messages, code listings, and command samples, as well as filenames. In code listings, italic monospace type is used for placeholder text. Code listings are colorized similar to the way they are colorized in Visual Studio. Blue monospace type is used for XML elements and C#/C++ keywords, brown monospace type is used for XML element names and C#/C++ strings, green monospace type is used for comments, red monospace type is used for XML attributes, and teal monospace type is used for type names in C# and C++. Throughout this book, you’ll find a number of sidebar elements: FA Q DIGGING DEEPER What is a FAQ sidebar? Digging Deeper Sidebars ? A FAQ sidebar presents a question A Digging Deeper sidebar presents advanced or readers might have regarding the subject more detailed information on a subject than is matter in a particular spot in the book—and provided in the surrounding text. Think of Dig- then provides a concise answer. ging Deeper material as stuff you can look into if you’re curious but can ignore if you’re not. TIP WARNING A tip is a bit of information that can help A warning alerts you to an action or a you in a real-world situation. Tips often offer condition that can lead to an unexpected shortcuts or alternative approaches to or unpredictable result—and then tells you produce better results or to make a task how to avoid it. easier or quicker. From the Library of Wow! eBook PART I Background IN THIS PART CHAPTER 1 Why WPF, and What About Silverlight? 9 CHAPTER 2 XAML Demystified 21 CHAPTER 3 WPF Fundamentals 73 From the Library of Wow! eBook This page intentionally left blank From the Library of Wow! eBook CHAPTER 1 IN THIS CHAPTER. A Look at the Past Why WPF, and What. Enter WPF About Silverlight?. The Evolution of WPF. What About Silverlight? In movies and on TV, the main characters are typically an exaggeration of the people you encounter in real life. They’re more attractive, they react more quickly, and they somehow always know exactly what to do. The same could be said about the software they use. This first struck me back in 1994 when watching the movie Disclosure, starring Michael Douglas, Demi Moore, and an email program that looks nothing like Microsoft Outlook! Throughout the movie, we’re treated to various visual features of the program: a spinning three-dimensional “e,” messages that unfold when you open them and crumple when you delete them, hints of inking support, and slick animations when you print messages. (The email program isn’t even the most unrealistic software in the movie. I’ll just say “virtual reality database” and leave it at that.) Usability issues aside, Hollywood has been telling us for a long time that software in the real world isn’t as compelling as it should be. You can probably think of several examples on your own of TV shows and movies with comically unrealistic software. But lately, real-world software has been catching up to Hollywood’s standards! You can already see it in traditional operating systems (yes, even in Windows), on the web, and in software for devices such as the iPhone, iPad, Zune, TiVo, Wii, Xbox, Windows phones, and many more. Users have increasing expecta- tions for the experience of using software, and companies are spending a great deal of time and money on user inter- faces that differentiate themselves from the competition. This isn’t limited to consumer-facing software; even busi- ness applications and internal tools can greatly benefit from a polished user interface. From the Library of Wow! eBook 10 CHAPTER 1 Why WPF, and What About Silverlight? With higher demands placed on user interfaces, traditional software development processes and technologies often fall short. Modern software usually needs to support rapid iteration and major user interface changes throughout the process—whether such changes are driven by professional graphic designers, developers with a knack for design- ing user interfaces, or a boss who wants the product to be more “shiny” and animated. For this to be successful, you need technology and tools that make it natural to separate the user interface from the rest of the implementation as much as possible and to decou- ple visual behavior from the underlying program logic. Developers should be able to create a fully functional “ugly” application that designers can directly retheme without requiring developers to translate their artwork. The Win32 style of programming, in which controls directly contain code to paint and repaint themselves, makes rapid user interface iteration far too difficult for most projects. In 2006, Microsoft released a technology to help people create 21st-century software that meets these high demands: Windows Presentation Foundation (WPF). With the release of WPF 4 in 2010, the technology is better than ever at delivering amazing results for just about any kind of software. Almost a decade after Tom Cruise helped popularize the idea of multi-touch computer input in the movie Minority Report, and after successful multi- touch implementations in a variety of devices (most notably the iPhone), WPF 4 and Windows 7 are bringing multi-touch to the masses. Hollywood better start coming up with some fresh ideas! A Look at the Past The primary technologies behind many Windows-based user interfaces—the graphics device interface (GDI) and USER subsystems—were introduced with Windows 1.0 in 1985. That’s almost prehistoric in the world of technology! In the early 1990s, OpenGL (created by Silicon Graphics) became a popular graphics library for doing advanced two-dimen- sional (2D) and three-dimensional (3D) graphics on both Windows and non-Windows systems. This was leveraged by people creating computer-aided design (CAD) programs, scientific visualization programs, and games. DirectX, a Microsoft technology introduced in 1995, provided a new high-performance alternative for 2D graphics, input, communi- cation, sound, and eventually 3D (introduced with DirectX 2 in 1996). Over the years, many enhancements have been made to both GDI and DirectX. GDI+, introduced in the Windows XP time frame, tried to improve upon GDI by adding support for features such as alpha blending and gradient brushes. It ended up being slower than GDI due to its complexity and lack of hardware acceleration. DirectX (which, by the way, is the technology behind Xbox) continually comes out with new versions that push the limits of what can be done with computer graphics. With the introduction of.NET and managed code in 2002, developers were treated to a highly productive model for creating Windows (and web) applications. In this world, Windows Forms (built on top of GDI+) became the primary way a C#, Visual Basic, and (to a lesser degree) C++ developer started to create new user interfaces on Windows. Windows Forms has been a successful and productive technology, but it still has all the fundamental limitations of GDI+ and USER. From the Library of Wow! eBook Enter WPF 11 Starting with DirectX 9, Microsoft shipped a DirectX framework for managed code (much like it shipped libraries specifically for Visual Basic in the past), which eventually was 1 supplanted by the XNA Framework. Although this enables C# developers to use DirectX without most of the complications of.NET/COM interoperability, these managed frame- works aren’t significantly easier to use than their unmanaged counterparts unless you’re writing a game. (The XNA Framework makes writing a game easier because it includes new libraries specifically for game development and works with compelling tools such as the XNA Framework Content Pipeline and XNA Game Studio Express.) So although you could have developed a Windows-based email program with the 3D effects seen in Disclosure ever since the mid-1990s with non-GDI technologies (actually, probably mixing DirectX or OpenGL with GDI), such technologies are rarely used in mainstream Windows applications even more than a decade later. There are several reasons for this: The hardware required to get a decent experience hasn’t been ubiquitous until recently, it has been at least an order of magnitude harder to use alternative tech- nologies, and GDI-based experiences have been considered “good enough.” Graphics hardware continues to get better and cheaper and consumer expectations continue to rise, but until WPF, the difficulty of creating modern user experiences had not been addressed. Some developers would take matters into their own hands to get cooler- looking applications and controls on Windows. A simple example of this is using bitmaps for buttons instead of using the standard button control. These types of customizations can not only be expensive to develop, but they also often produce a flakier experience. Such applications often aren’t as accessible as they should be, don’t handle high dots-per- inch (DPI) settings very well, and have other visual glitches. Enter WPF Microsoft recognized that something brand new was needed that escaped the limitations of GDI+ and USER yet provided the kind of productivity that people enjoy with frame- works like Windows Forms. And with the continual rise of cross-platform applications based on HTML and JavaScript, Windows desperately needed a technology that’s as fun and easy to use as these, yet with the power to exploit the capabilities of the local computer. Windows Presentation Foundation (WPF) is the answer for software developers and graphic designers who want to create modern user experiences without having to master several difficult technologies. Although “Presentation” sounds like a lofty term for what I would simply call a user interface, it’s probably more appropriate for describing the higher level of visual polish that’s expected of today’s applications and the wide range of functionality included in WPF! The highlights of WPF include the following:. Broad integration—Prior to WPF, a Windows developer who wanted to use 3D, video, speech, and rich document viewing in addition to normal 2D graphics and controls would have to learn several independent technologies with a number of inconsistencies and attempt to blend them together without much built-in support. But WPF covers all these areas with a consistent programming model as well as tight integration when each type of media gets composited and rendered. You can apply From the Library of Wow! eBook 12 CHAPTER 1 Why WPF, and What About Silverlight? the same kind of effects consistently across different media types, and many of the techniques you learn in one area apply to all the other areas.. Resolution ind

Tags

WPF Microsoft .NET application software programming
Use Quizgecko on...
Browser
Browser