Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Pro WPF and Silverlight MVVM effective Application Development
Nội dung xem thử
Mô tả chi tiết
this print for content only—size & color not accurate 7.5 x 9.25 spine = 0.75" 272 page count 360 PPI Hall WPF and Silverlight MVVM
THE EXPERT’S VOICE® IN WPF
Pro
WPF and Silverlight
MVVM
Effective Application Development with
Model-View-ViewModel
CYAN
MAGENTA
YELLOW
BLACK
PANTONE 123 C
Gary McLean Hall
Companion
eBook
Available
Harness the power of WPF and Silverlight to
produce clean, testable, maintainable code
BOOKS FOR PROFESSIONALS BY PROFESSIONALS®
Pro WPF and Silverlight MVVM
WPF and Silverlight are unlike any other user interface technologies. They have
been built to a new paradigm that—if harnessed correctly—can yield unprecedented power and performance. This book shows you how to control that
power to produce clean, testable, maintainable code.
Design and development experts now recognize that any non-trivial WPF
or Silverlight application needs to be designed around the Model-ViewViewModel (MVVM) design pattern in order to unlock the technology’s full
data-binding potential. But many coders still rely solely on programmatic
interaction between controls, because it's been hard for many to trust the WPF
data-binding technologies.
Pro WPF and Silverlight MVVM shows you why that trust has been earned.
Inside, discover how to create fast, scalable, and maintainable applications
using Silverlight and WPF. With this book, you’ll learn how to:
• Split view and model code apart to achieve a separation of concerns
• Implement a ViewModel layer that mediates between the view and model
• Apply automated unit tests to verify the quality of production code
• Validate user input with a variety of techniques
• Integrate a data access layer for persistently storing objects
Gary McLean Hall
Shelve in:
.NET
User level:
Intermediate–Advanced
THE APRESS ROADMAP
Introducing
Silverlight 4
Pro
ASP.NET MVC
Framework
Pro
WPF in C# 2010
Pro
Silverlight 4 in C#
Pro
WPF and
Silverlight MVVM
www.apress.com
SOURCE CODE ONLINE
Companion eBook
See last page for details
on $10 eBook version
ISBN 978-1-4302-3162-2
9 781430 231622
5 49 9 9
Pro
i
Pro WPF and
Silverlight MVVM
Effective Application Development with
Model-View-ViewModel
■ ■ ■
Gary McLean Hall
ii
Pro WPF and Silverlight MVVM: Effective Application Development with Model-View-ViewModel
Copyright © 2010 by Gary McLean Hall
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-3162-2
ISBN-13 (electronic): 978-1-4302-3163-9
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.
President and Publisher: Paul Manning
Lead Editor: Jonathan Hassell
Technical Reviewer: Nathan Kannan
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick,
Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank
Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Debra Kelly
Copy Editors: Mary Behr and Sharon Terdeman
Compositor: MacPS, LLC
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com.
For information on translations, please e-mail [email protected], or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com.
iii
For my wife, Victoria
iv
Contents at a Glance
■Contents ................................................................................................................ v
■About the Author ................................................................................................... x
■About the Technical Reviewer .............................................................................. xi
■Acknowledgments ............................................................................................... xii
■Introduction ....................................................................................................... xiii
■Chapter 1: Overview of WPF and Silverlight ......................................................... 1
■Chapter 2: DataBinding ....................................................................................... 21
■Chapter 3: Model-View Separation ..................................................................... 55
■Chapter 4: The ViewModel .................................................................................. 81
■Chapter 5: Events and Commands .................................................................... 111
■Chapter 6: Validation ......................................................................................... 129
■Chapter 7: Unit Testing ...................................................................................... 145
■Chapter 8: Data Access Layer ........................................................................... 163
■Chapter 9: Application Support ......................................................................... 185
■Chapter 10: Sample Application ........................................................................ 205
■Index ................................................................................................................. 243
v
Contents
■Contents at a Glance ............................................................................................ iv
■About the Author ................................................................................................... x
■About the Technical Reviewer .............................................................................. xi
■Acknowledgments ............................................................................................... xii
■Introduction ........................................................................................................ xiii
■Chapter 1: Overview of WPF and Silverlight ......................................................... 1
WPF and Silverlight ......................................................................................................... 1
What Is WPF? ......................................................................................................................................... 1
What Is Silverlight? ................................................................................................................................ 5
Differences Between WPF and Silverlight .............................................................................................. 7
Multi-Target Platforms ........................................................................................................................... 9
XAML ............................................................................................................................. 13
Declarative User Interfaces .................................................................................................................. 13
XAML Elements .................................................................................................................................... 14
XAML Features ..................................................................................................................................... 16
User Experience vs. User Interface ............................................................................... 18
Summary ....................................................................................................................... 19
■Chapter 2: DataBinding ....................................................................................... 21
The Power of DataBinding with XAML .......................................................................... 21
Dependency Objects ............................................................................................................................ 21
Dependency Properties ........................................................................................................................ 23
Binding Sources ................................................................................................................................... 26
■ CONTENTS
vi
Binding Modes ..................................................................................................................................... 28
The DataContext ................................................................................................................................... 30
Advanced DataBinding .................................................................................................. 31
Binding Parameters ............................................................................................................................. 31
Data Conversion ................................................................................................................................... 35
ObjectDataProvider .............................................................................................................................. 42
Debugging DataBindings ...................................................................................................................... 46
Templating ........................................................................................................................................... 49
Summary ....................................................................................................................... 53
■Chapter 3: Model-View Separation ..................................................................... 55
Separation of Concerns ................................................................................................. 55
Dependencies ...................................................................................................................................... 55
MVVM Alternatives ............................................................................................................................... 59
The Model ..................................................................................................................... 66
Encapsulation ....................................................................................................................................... 66
Don’t Repeat Yourself (DRY) ................................................................................................................. 67
You Ain’t Gonna Need It (YAGNI) .......................................................................................................... 69
The Law of Demeter ............................................................................................................................. 70
Test-Driven Development .................................................................................................................... 71
The View ....................................................................................................................... 73
Data Representation ............................................................................................................................ 73
User Input ............................................................................................................................................. 73
Data Binding ......................................................................................................................................... 74
Separating Model from View ......................................................................................... 75
The Mediator Pattern ........................................................................................................................... 75
Other Model-View-X Implementations ................................................................................................. 77
You Gotta Keep ’Em Separated ............................................................................................................ 78
Summary ....................................................................................................................... 79
■Chapter 4: The ViewModel .................................................................................. 81
First ViewModel ............................................................................................................ 81
■ CONTENTS
vii
The MVVM Template Project ................................................................................................................ 81
.NET Framework Interfaces and Classes ...................................................................... 90
Observer Pattern .................................................................................................................................. 90
INotifyPropertyChanged Interface ........................................................................................................ 91
Observable Collections ......................................................................................................................... 92
CollectionViewSource .......................................................................................................................... 94
Constructing ViewModels .................................................................................................................... 96
Handling Concurrency ................................................................................................. 100
Threading ........................................................................................................................................... 100
Threading Problems In WPF and Silverlight ....................................................................................... 104
Updating the UI .................................................................................................................................. 107
Summary ..................................................................................................................... 110
■Chapter 5: Events and Commands .................................................................... 111
Events ......................................................................................................................... 111
Events in .NET .................................................................................................................................... 111
Events in WPF and Silverlight ............................................................................................................ 112
Commands .................................................................................................................. 115
Command Pattern .............................................................................................................................. 116
The RelayCommand ........................................................................................................................... 119
Attached Command Behavior ............................................................................................................. 126
Avoiding Events Using Dependency Injection .................................................................................... 126
Summary ..................................................................................................................... 128
■Chapter 6: Validation ......................................................................................... 129
The Validation Process ................................................................................................ 130
Binding Validation Rules ............................................................................................. 131
ValidationRule Class ........................................................................................................................... 131
Exceptions for Validation .................................................................................................................... 133
A Validation Framework ..................................................................................................................... 135
IDataErrorInfo Interface ...................................................................................................................... 135
DataErrorValidationRule Class ........................................................................................................... 139
■ CONTENTS
viii
Validation in Silverlight ............................................................................................... 139
Visually Formatting Validation Errors .......................................................................... 143
Validation.ErrorTemplate Attached Property ...................................................................................... 143
Validation.HasError Attached Property ............................................................................................... 143
Summary ..................................................................................................................... 144
■Chapter 7: Unit Testing ...................................................................................... 145
The Importance of Testing .......................................................................................... 145
Traditional Testing ............................................................................................................................. 145
What Is Unit Testing? ......................................................................................................................... 149
Why Unit Test? ................................................................................................................................... 151
How to Unit Test .......................................................................................................... 152
Unit Testing with Visual Studio 2010 ................................................................................................. 152
Writing Tests ...................................................................................................................................... 158
Summary ..................................................................................................................... 162
■Chapter 8: Data Access Layer ........................................................................... 163
Object-Relational Dichotomy ...................................................................................... 163
DAL Implementations .................................................................................................. 172
Manual Implementation ..................................................................................................................... 172
Third-Party Implementations ............................................................................................................. 176
Supporting Patterns .................................................................................................... 180
The Repository Pattern ....................................................................................................................... 180
Unit of Work ....................................................................................................................................... 181
Creating the Data Schema .......................................................................................... 182
Generate, Not Create .......................................................................................................................... 182
Summary ..................................................................................................................... 183
■Chapter 9: Application Support ......................................................................... 185
Serialization ................................................................................................................ 186
Serializing POCOs ............................................................................................................................... 186
Extensibility ................................................................................................................. 192
■ CONTENTS
ix
Why Extend? ...................................................................................................................................... 192
Using Managed Extensibility Framework ........................................................................................... 193
Extending A WPF Application ............................................................................................................. 197
Limitations ......................................................................................................................................... 202
Summary ..................................................................................................................... 203
■Chapter 10: Sample Application ........................................................................ 205
Requirements .............................................................................................................. 205
The Application .................................................................................................................................. 205
Model and Tests .......................................................................................................... 206
Money ................................................................................................................................................ 206
Account .............................................................................................................................................. 211
ViewModel and Tests .................................................................................................. 220
MainWindowViewModel ..................................................................................................................... 220
View ............................................................................................................................ 228
Summary ..................................................................................................................... 241
■Index ................................................................................................................. 243
■ CONTENTS
x
About the Author
■ Gary McLean Hall lives in Leeds, England, with his wife, Victoria, and their dog,
Isabella. He is the director of Four Minute Mile Ltd, a software development
consultancy specializing in Microsoft technologies.
xi
About the Technical Reviewer
■ Nathan Kannan serves as Director of GIS (Geographic Information System) at Sentinel USA, a
company that specializes in providing GIS services and consulting to the utility industry. Mr. Kannan
provides a wealth of talent and expertise to Sentinel USA and has contributed to the success of several
high-profile development projects in the GIS technology arena. Mr. Kannan holds both a master’s
degree in Geographic Information Systems and Mapping (MS GIS) from The Ohio State University and a
bachelor’s degree in Civil Engineering (BE) from PSG College of Technology, India. His professional
skills and contributions are in the fields of GIS Software and Custom Application Development,
Advanced Spatial Database and Data Structure, Computational Cartography, GPS, and
Photogrammetry. He is the inventor and one of the authors of the patent “Distance Correction for Utility
Damage Prevention System, Publication No: WO/2007/067898, Publication Date: 14.06.2007.”
■ CONTENTS
xii
Acknowledgments
Thanks to my wife, Victoria, for being perfect in every way.
Thanks to my parents, Pam and Les, for funding such an expensive hobby and underwriting the dial-up
Internet bills of the late-90s.
Thanks to my brother, Darryn, for being a constant best friend, his wife, Jo, and their beautiful daughter,
Eleanor.
Thanks to my Granda George for his selfless generosity.
Thanks to my editor, Debra Kelly, whose patience knows no bounds!
Thanks to my dog, Isabella, for her unconditional loyalty.
Thanks to everyone who has taught me, whether they knew it or not.
xiii
Introduction
This book was conceived from a need to explain the MVVM pattern and how it helps structure WPF and
Silverlight applications. I had worked on a number of projects where these technologies were used but
general best practices were ignored because no one had formally explained the MVVM pattern and how
it compared to other patterns such MVP and MVC.
In Chapter 1, WPF and Silverlight will be explored in some detail and their respective features
highlighted.
Chapter 2 introduces the foundation of the MVVM pattern: the databinding model that eclipses the
equivalent functionality of Windows Forms or ASP.NET.
Chapter 3 explains why the model and the view must be separated in an application and provides
various tips and tricks that can help achieve a strict separation of concerns.
Chapter 4 introduces the ViewModel that sits between the model and view layers and mediates between
the two.
Chapter 5 discusses commands and events, weighing up the pros and cons of each.
Chapter 6 examines various options for implementing validation into an application.
Chapter 7 explores the best side effects of the separation of concerns achieved through MVVM:
testability and unit testing.
Chapter 8 outlines how to implement a Data Access Layer into a Silverlight or WPF application and how
the ViewModel can interact with this layer.
Chapter 9 explains how to serialize an object graph using WPF and MVVM, as well as exploring how WPF
and Silverlight applications can be extended.
Chapter 10 ends the book with a sample application that ties together many of the features covered
along the way.