logo资料库

MVVM Survival Guide for Enterprise Architectures in Silverlight ....pdf

第1页 / 共491页
第2页 / 共491页
第3页 / 共491页
第4页 / 共491页
第5页 / 共491页
第6页 / 共491页
第7页 / 共491页
第8页 / 共491页
资料共491页,剩余部分请下载后查看
Cover
Copyright
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Table of Contents
Preface
Chapter 1: Presentation Patterns
The Project Billing sample application
Types of state
History of presentational patterns
Monolithic design
The problems with monolithic design
Data service stub
Monolithic Project Billing sample
ProjectsView
Running the sample
Takeaways
Rapid application development
RAD Project Billing sample
Takeaways
MVC
View
Controller
Model
Layered design
The layers
MVC with layered design
MVC Project Billing sample
Model
Controller
View
How it works
Takeaways
Memory leaks
MVP
MVP Project Billing sample
Model
View
Presenter
Main window
How it works
Takeaways
Summary
Chapter 2: Introduction to MVVM
History
Structure
Pure MVVM
View
View Model
WPF and Silverlight enablers
Dependency Properties
Dependency property inheritance
Rich data binding
INotifyCollectionChanged and ObservableCollection<>
Automatic dispatching
Triggers
Styles
Control Templates
Data templates
Commands
MVVM project billing sample
MVVM design
View Models
Model
Code
ProjectsModel
ProjectViewModel
ProjectsViewModel
WPF UI
Silverlight UI
Benefits of MVVM
MVVM and humble views
Issues and pain points of MVVM
MVVM Light
Summary
Chapter 3: Northwind – Foundations
Northwind requirements
Presentation tier foundation
Locator pattern
Data access tier
Listing the customers
Unit testing getting customers
Using an isolation framework
Adding tabs
Viewing customer details
Viewing details for one customer
Testing CustomerDetailsViewModel
Wiring up the customer list box
Testing ShowCustomerDetails()
Summary
Chapter 4: Northwind—Services and Persistence Ignorance
Adding a Service Layer
Integrating the Service Layer
Persistence ignorance and custom models
Trade-offs of generated models
Adding persistence ignorance
Adding unit tests
Summary
Chapter 5: Northwind—Commands and User Inputs
Pure MVVM
Making it easier with frameworks
Updating customer details
Testing and updating customer details
Gestures, events, and commands
InputBindings
KeyBinding
MouseBinding
Using code behind
Event to command
Attached Behavior
Using MVVM Light
Summary
Chapter 6: Northwind—Hierarchical View Model and IoC
Adding orders to customer details
Service layer
Application layer
Presentation layer
View Models
Views
Take aways
Viewing order details
ToolManager
Inversion of Control frameworks
IoC designs
Adding an IoC container to Northwind
Order details
Summary
Chapter 7: Dialogs and MVVM
Should we make a compromise?
Dialog service
Using DataTemplates with DialogService
Convention over configuration
Mediators
Attached behaviors
Summary
Chapter 8: Workflow-based MVVM Applications
WF for business rules execution
Handling delays in rules execution
WF for controlling application flow
Summary
Chapter 9: Validation
Validations and dependency properties
Error templates
Validation in MVVM-based applications
Validation rules
Using validation rules
Specializing validation rules—supporting parameters
Validation rules and converters
Validation mechanism in WPF and Silverlight
IDataErrorInfo
Validation states
Limitations and gotchas
INotifyDataErrorInfo
Enterprise library validation application block
Complex business rules
Error notifications
Error message box
Highlighting fields
Error messages in the tooltip
Error messages beside the control
Validation summary pane
Flip controls
Summary
Chapter 10: Using Non-MVVM Third-party Controls
Using attached behaviors
Using binding reflector
readonly CLR properties (with no change notification support)
Using .NET 4.0 dynamic
Using MVVM adapters
Summary
Chapter 11: MVVM and Application Performance
Asynchronous binding
Asynchronous View Model construction
Priority binding
Virtualization and paging
Using BackgroundWorker
Targeting system configuration
Event Throttling
Lazy Initialization
Summary
Appendix A: MVVM Frameworks
Appendix B: Binding at a Glance
Basics
Validation
ValidationRules
IDataErrorInfo
INotifyDataErrorInfo [.net 4.5]
Enterprise Library 5.0 Validation Application Block
Windows WF
Validation.ErrorTemplate
Static properties/fields
Executing code in DataContext
Binding to DataContext[DC]
Resources
Types with default constructor
XmlDataProvider
ObjectDataProvider
Binding to resource
Static resource
Dynamic resource
Updating source
Binding.UpdateSourceTrigger
Binding.Delay: [.net 4.5] [Binding.Mode:TwoWay / OneWayToSource ]
Mode [Binding.Mode] [T:Target, S:Source]
Binding to other elements in the view
ElementName
RelativeSource
Conversion
Binding.StringFormat [SF]
Converter [C]
Performance
Async binding
ObjectDataProvider.IsAsynchronous
PriorityBinding
Index
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF Eliminate unnecessary code by taking advantage of the MVVM pattern—less code, fewer bugs Ryan Vice Muhammad Shujaat Siddiqi BIRMINGHAM - MUMBAI
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF Copyright © 2012 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2012 Production Reference: 1010812 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84968-342-5 www.packtpub.com Cover Image by Tony Shi (shihe99@hotmail.com)
Credits Project Coordinator Abhishek Kori Proofreader Lesley Harrison Indexer Rekha Nair Graphics Manu Joseph Production Coordinator Melwyn D'sa Cover Work Melwyn D'sa Authors Ryan Vice Muhammad Shujaat Siddiqi Reviewer Kanishka (Ken) Abeynayake Acquisition Editor Dhwani Devater Lead Technical Editor Dhwani Devater Technical Editors Felix Vijay Manasi Poonthottam Lubna Shaikh Copy Editors Brandt D'Mello Laxmi Subramanian Alfida Paiva
Foreword Rich client development remains one of the most popular forms of application development, both from a user and a developer point of view. While nobody denies the importance of thin-client interface technologies such as HTML(5), it is clear that consumers and enterprises alike enjoy using applications that provide a rich, powerful, productive, and sometimes fun experience. Evidence ranges from the current App Craze on mobile devices to the long-running history of rich business applications deployed by many businesses of all sizes. Many of the most successful applications and systems, measured in commercial success and/or popularity, are either entirely based on Rich Client technology or make Rich Clients part of the mix. If you are a Microsoft developer (and if you are reading this book, the chances are that you are), you find yourself in the lucky position of getting a chance to use one of the best, if not the best, sets of Rich Client development technologies and tools. The paradigm first introduced by WPF (then known under its Avalon code name) and the XAML declarative approach have turned out to be a super-productive, highly maintainable, and highly reusable approach. The technologies are easy to use once the developer gets acquainted with the ideas behind the setup of XAML-based systems. It is true that there is a learning curve. As an industry, we have used the same UI development paradigm across many languages, systems, and even platforms for a very long period of time, reaching back all the way to MS DOS. The drop a control on a form, set a few properties, and wire up some event handlers approach can be found almost universally in pre-XAML scenarios ranging from Visual Basic, to C++, PowerBuilder, Delphi, Visual FoxPro, .NET Windows Forms, ASP.NET WebForms, even standalone HTML scenarios, and many more. XAML breaks that mold. Yes, you can still employ the old paradigm, but you can reap significant benefits by following the new ideas. By reading this book, you are well on your way down that path, and you will find that while there is a hump in the learning curve you need to get over, there also is a significant downward slope on the other side of that hump. While many environments retain a high level of difficulty even once you achieve a high degree of familiarity, WPF is different in that things tend to be pretty straightforward once you know how to do things the right way.
WPF has become the de-facto standard for Windows Desktop Application development. It is now a well-established technology that has superseded the older Windows Forms (WinForms) framework. Microsoft uses WPF in many of its own products and WPF has been continually developed for a number of years and across a number of versions and major releases. While other development environments may be flashier, and technologies like HTML5 get the limelight, I can tell based on personal experience that WPF seems to be a secret hot technology. This may be anecdotal evidence based on my own experiences only, but my experience draws on my interactions not just with our consulting and custom software customers, but also on the interactions with a hundreds of people who attend training classes we teach, thousands of people I interact with at various developer events, and the tens of thousands of people I interact with one way or another as readers of CODE Magazine. In short, WPF is a very popular development environment that is used for a large number of highly strategic development projects. WPF developers are also highly sought after. While there may not be a need for as many WPF developers as there is for HTML developers, the demand for WPF developers is much higher. In other words, while the world generally needs more HTML developers and designers than WPF equivalents, there is no shortage of those HTML skills. I do not mean to take anything away from the many highly skilled HTML experts (and the same goes for many other platforms and technologies). However, those skills are relatively easily available. WPF skills, on the other hand, are much harder to come by and thus represent a more valuable expertise. Skilled WPF developers routinely command a higher salary or hourly rate. A fact you are probably happy to learn if you are interested in reading this book. ;-) While this book focuses on WPF, many of the things you learn here will serve you well beyond WPF. The XAML Paradigm is of course used in other environments. Silverlight in its original form as a browser plugin is one such example that has grown out of WPF. While browser plugin technology may have seen its best days as far as strategic importance goes, Silverlight still goes down in history as one of the fastest growing and most rapidly adopted developer technologies ever. Silverlight will also be here to stay for some time to come. While I would not recommend starting new projects in Silverlight unless you have a very good and specific reason to do so, you are probably OK using Silverlight for a bit longer if you have already travelled down that path. For new projects, however, I would recommend WPF. It is important to remember that the ideas behind Silverlight are not just useful in browser plugins. Silverlight for Windows Phone is turning out to be a beautiful and highly productive development environment embraced by developers. For mobile development, one first chooses the platform of course. If that platform is iOS, Apple's development environments and languages are a given. If the platform is Android,
one probably ends up with Java. It is too bad one cannot choose Microsoft's version of Silverlight for Windows Phone to develop on any of these other mobile platforms, because I would personally choose it any day over any of the other options based on pure productivity and development joy. And the story continues. XAML is used as one of the cornerstones in Windows 8's new Metro user interface mode. So everything you learn in this book will be of use to you in the bold new world of Windows 8 development as well. Windows 8 Metro also supports a proprietary development model based on HTML5 and JavaScript, which will be on equal footing with XAML. The jury is still out and it is too early to tell (as I am writing these lines, we are still at least a half a year away from the Windows 8 ship date) but based on what we see at events and from readership reactions through CODE Magazine, people seem to be most interested in the XAML development option. A biased result perhaps (after all, current WPF and Silverlight developers are probably most likely to be the first ones in as far as Metro development goes), but it is still interesting to see that XAML development is alive and well, and expected to enjoy a bright future. Microsoft is planning to ship Windows 8 with two modes; one known as Metro as well as the more conventional Desktop mode, which largely resembles Windows 7's desktop. Which brings us right back to WPF, because all WPF applications will continue to work just fine in Windows 8's Desktop mode. Either way you turn it, the XAML family of technologies is not a bad family to be part of. We are certainly very happy to base a lot of our efforts on these technologies and have a high degree of comfort moving forward with that approach. But not all WPF development is created equal. There are a lot of different scenarios and approaches. Some good, some bad. One approach may work well in some scenarios while it doesn't work well at all in others. As in all engineering disciplines, knowing the pros and cons of each tool in the toolbox is an important aspect of engineering know-how. With that said however, it is clear that MVVM is a very valuable pattern for a lot of WPF-based applications (and XAML-based applications, in general). If done right, MVVM leads to a range of different advantages ranging from quality to maintainability, reusability, even developer productivity, and more. As with most powerful tools, the power can be wielded both for good and evil. Yes, it is possible to create horrible monstrosities that are hard and slow to develop and result in inflexible and slow applications. If that is the outcome, the developers and architects did a bad job in evaluating the tools at their disposal and made ill-advised choices in how to wield them. Luckily, the book you are currently reading is going to be a valuable first step in learning how to avoid such mistakes and instead unleash the incredible power of MVVM and many of the associated techniques.
分享到:
收藏