YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 1: Programming with MVVM

Programming with MVVM

Miguel A. CastroArchitectIDesign

DEV206

Page 2: Programming with MVVM

Agenda

XAML Data BindingWhat is MVVMImplementing the Pattern (and sticking to it)Adding CommandingUnit TestingAdvanced Features

Page 3: Programming with MVVM

Data Binding

Extremely powerful with XAMLEverything binds (to everything else)Every tag has DataContext property

Value becomes underlying binding sourceProvides values from tag & down visual tree

Underlying binding object should implement INotifyPropertyChanged interfaceXAML binding attributes provide additional characteristicsMode, UpdateSourceTrigger, Converter

Page 4: Programming with MVVM

XAML Data Binding<Window>

<Grid><Label Content=“{Binding Name}”

Width=“{Binding Size}” /> ...…………………………………………………………………………………this.DataContext = myObj;

where myObj contains:string Namedouble Size

Page 5: Programming with MVVM

What is MVVM?

Pattern made specially for bindingClass provides the binding source for the entire viewEncapsulates logic for the view

Provides state and behaviorLoosely coupled to the view

Page 6: Programming with MVVM

What is MVVM?

Data Access Layer

Domain Layer

ViewModel Layer

View (XAML) Layer

Data Storage Layer

Page 7: Programming with MVVM

Goals of MVVM

Make the view completely “State Driven”Fill in for model short-comingsDecouple state and behavior from viewProvide ability to unit test

Reduction or even elimination of the code-behind class

Page 8: Programming with MVVM

Rules of MVVM

ViewModel should have NO knowledge of the ViewFor navigation, ViewModel can raise an event that View can hook into

Unless using ViewModel switching & Data Templates (later)View should have a loose coupling to ViewModel (not until runtime if possible)ViewModel can expose individual model properties or model as a whole

Page 9: Programming with MVVM

Implementing the Pattern

A ViewModel is just a class thatWraps one or more domain modelsProvides property notificationProvides validation notification (optional)Exposes bindable properties (or model)Contains commanding behaviorCan be tested completely independent of the viewCan fire events back to the view

Page 10: Programming with MVVM

Connecting to View

ViewModel class becomes the “DataContext” of the ViewWindow or UserControl

Can be set anywhere convenient View can optionally hook into ViewModel events

Good for view navigation

Page 11: Programming with MVVM

Implementing the MVVM Pattern

Demo

Page 12: Programming with MVVM

Commanding

XAML TechnologyNot specifically MVVM-related

Works great with MVVMCommand classes

Inherit ICommandUsed with implementers of ICommandSource

Provide execution and determination of execution

Page 13: Programming with MVVM

Commanding

Command Basics

Demo

Page 14: Programming with MVVM

Commanding in MVVM

Sometimes a command needs access to ViewModel stateSaving of data entered by user

Command classes don’t “belong” to a ViewModelNeed way to hook classes together

Command execution needs to access VM state

Page 15: Programming with MVVM

Commanding in MVVM

Technique 1:Receive copy of ViewModel into command constructor

Technique 2:Use Delegate/Relay Command patternAllows passing of method pointers into command

Methods reside in ViewModel

Which technique is used depends on command reusability necessities

Page 16: Programming with MVVM

Commanding

Commands in MVVM

Demo

Page 17: Programming with MVVM

Putting It All Together

Think in State-Driven termsIf View has requirement, ask:

What state and behavior does the ViewModel have to expose in order to satisfy the requirement?

ExerciseProvide a view with a label to be displayed in one of two colorsProvide two buttons used to alter the colors of the labelEnable or disable the buttons accordingly when not usefulAllow for proper unit testing

Page 18: Programming with MVVM

Before & After MVVM

BEFORE

View shows label and buttonsButton click events change color of labelButton click events disable button just clicked and enable other button

AFTER

View shows labels and buttonsView bound to ViewModelLabel color bound to propertyButtons bound to commandsCommand argument provides colorCommand execution changes color propertyCommand determination depends on current color

Page 19: Programming with MVVM

MVVM Exercise

Before & After MVVM

DEMO

Page 20: Programming with MVVM

Unit Testing

ViewModel is totally decoupled from ViewHas no dependency on View classCan even reside in separate assemblyCan be instantiated like regular classUnit test can test properties (if needed)Unit test can set state and call upon command execution

Page 21: Programming with MVVM

Unit Testing

Testing the MVVM Exercise

DEMO

Page 22: Programming with MVVM

ViewModel-First

Views contain other ViewsSame hierarchy for ViewModels

ViewModel exposes other ViewModels as stateCommands cause ViewModel “flipping”Data Templates provide VM-V mapping

Silverlight requires a Type-Converter techniqueCan concentrate on the logic of what ViewModel to use when and why – independent of actual View that will show

Page 23: Programming with MVVM

View Switching

ViewModel-First Technique

DEMO

Page 24: Programming with MVVM

Where to next?

Further technologies intertwined with MVVMType ConvertersValidation TechniquesDesign-Time DataDependency InjectionFrameworks

Page 25: Programming with MVVM

Frameworks

Domain-Framework

Core-FrameworkViewModelBase

Customer-ViewModel

TabbedViewModel DialogViewModelToolViewModel RibbonTab-

ViewModel

Undoable-ViewModel

SaveableTabbed-ViewModel

Page Conductors

Validation Rules

View Bases

Type Converters

Event Argument Classes

Enums

CustomerGenInfo-ViewModel

CustomerProfile-ViewModel

CustomerOrders-ViewModel

CustomerBilling-ViewModel

Relay Command

ModelBase

ObjectBase

Page 26: Programming with MVVM

Frameworks

MVVM FoundationMVVM LightCaliburnCSLAPrismRefraction

Page 27: Programming with MVVM

Finalizer

ViewModels provide a great binding source for XAML viewsDecoupleness allows easy testingCan set up ViewModel inheritance chains for commonly used state or behavior

Not possible with code-behindMuch cleaner designTake the time to setup MVVM – it’ll be worth itUse or build a framework – at minimum, a base layer

Page 28: Programming with MVVM

Finalizer

Let your ViewModel evolve naturallyThink about ViewModel inheritance where applicableDon’t concentrate on code-behind elimination

It will happen naturally and eventuallyIn most cases, you may start out never using code-behind

Don’t forget your unit testsShould have one unit test per-ViewModel

Page 29: Programming with MVVM

References

Josh Smith’s Bloghttp://joshsmithonwpf.wordpress.com/

In the Box – MVVM TrainingKarl Shiffletthttp://karlshifflett.wordpress.com/2010/11/07/in-the-box-ndash-mvvm-training/Full kudos for the MVVM Before/After exercise

TONS of MVVM stuff on the web

Page 30: Programming with MVVM

DEV Track Resources

http://www.microsoft.com/visualstudio http://www.microsoft.com/visualstudio/en-us/lightswitch http://www.microsoft.com/expression/http://blogs.msdn.com/b/somasegar/http://blogs.msdn.com/b/bharry/http://www.microsoft.com/sqlserver/en/us/default.aspxhttp://www.facebook.com/visualstudio

Page 31: Programming with MVVM

Resources

www.microsoft.com/teched

Sessions On-Demand & Community Microsoft Certification & Training Resources

Resources for IT Professionals Resources for Developers

www.microsoft.com/learning

http://microsoft.com/technet http://microsoft.com/msdn

Learning

http://northamerica.msteched.com

Connect. Share. Discuss.

Page 32: Programming with MVVM

Complete an evaluation on CommNet and enter to win!

Page 33: Programming with MVVM

Scan the Tag to evaluate this session now on myTech•Ed Mobile

Page 34: Programming with MVVM

Miguel A. Castro

[email protected]@miguelcastro67www.dotnetdude.com

Stay in touch…

Page 35: Programming with MVVM