Top Banner
Programming with MVVM Miguel A. Castro Architect IDesign DEV206
35

Programming with MVVM

Feb 23, 2016

Download

Documents

zihna

DEV206. Programming with MVVM. Miguel A. Castro Architect IDesign. Agenda. XAML Data Binding What is MVVM Implementing the Pattern (and sticking to it) Adding Commanding Unit Testing Advanced Features. Data Binding. Extremely powerful with XAML Everything binds (to everything else) - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

DEV206: Programming with MVVM

Programming with MVVMMiguel A. CastroArchitectIDesignDEV2065/19/2011 6:06 PM 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

1AgendaXAML Data BindingWhat is MVVMImplementing the Pattern (and sticking to it)Adding CommandingUnit TestingAdvanced Features2Data BindingExtremely powerful with XAMLEverything binds (to everything else)Every tag has DataContext propertyValue becomes underlying binding sourceProvides values from tag & down visual treeUnderlying binding object should implement INotifyPropertyChanged interfaceXAML binding attributes provide additional characteristicsMode, UpdateSourceTrigger, Converter

3XAML Data Binding

...this.DataContext = myObj;

where myObj contains:string Namedouble Size4What is MVVM?Pattern made specially for bindingClass provides the binding source for the entire viewEncapsulates logic for the viewProvides state and behaviorLoosely coupled to the view5What is MVVM?Data Access LayerDomain LayerViewModel LayerView (XAML) LayerData Storage Layer6Goals of MVVMMake the view completely State DrivenFill in for model short-comingsDecouple state and behavior from viewProvide ability to unit test

Reduction or even elimination of the code-behind class7Rules of MVVMViewModel should have NO knowledge of the ViewFor navigation, ViewModel can raise an event that View can hook intoUnless 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 wholeImplementing the PatternA 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 view9 Connecting to ViewViewModel class becomes the DataContext of the ViewWindow or UserControlCan be set anywhere convenient View can optionally hook into ViewModel eventsGood for view navigationImplementing the MVVM PatternDemoCommandingXAML TechnologyNot specifically MVVM-relatedWorks great with MVVMCommand classesInherit ICommandUsed with implementers of ICommandSourceProvide execution and determination of executionCommandingCommand BasicsDemoCommanding in MVVMSometimes a command needs access to ViewModel stateSaving of data entered by userCommand classes dont belong to a ViewModelNeed way to hook classes togetherCommand execution needs to access VM state

Commanding in MVVMTechnique 1:Receive copy of ViewModel into command constructorTechnique 2:Use Delegate/Relay Command patternAllows passing of method pointers into commandMethods reside in ViewModel

Which technique is used depends on command reusability necessitiesCommandingCommands in MVVMDemoPutting It All TogetherThink 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

Before & After MVVMBEFORE

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

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 colorMVVM ExerciseBefore & After MVVMDEMOUnit TestingViewModel 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 executionUnit TestingTesting the MVVM ExerciseDEMOViewModel-FirstViews contain other ViewsSame hierarchy for ViewModelsViewModel exposes other ViewModels as stateCommands cause ViewModel flippingData Templates provide VM-V mappingSilverlight requires a Type-Converter techniqueCan concentrate on the logic of what ViewModel to use when and why independent of actual View that will showView SwitchingViewModel-First TechniqueDEMOWhere to next?Further technologies intertwined with MVVMType ConvertersValidation TechniquesDesign-Time DataDependency InjectionFrameworksFrameworksDomain-FrameworkCore-FrameworkViewModelBaseCustomer-ViewModelTabbedViewModelDialogViewModelToolViewModelRibbonTab-ViewModelUndoable-ViewModelSaveableTabbed-ViewModelPage ConductorsValidation RulesView BasesType ConvertersEvent Argument ClassesEnumsCustomerGenInfo-ViewModelCustomerProfile-ViewModelCustomerOrders-ViewModelCustomerBilling-ViewModelRelay CommandModelBaseObjectBaseFrameworksMVVM FoundationMVVM LightCaliburnCSLAPrismRefractionFinalizerViewModels provide a great binding source for XAML viewsDecoupleness allows easy testingCan set up ViewModel inheritance chains for commonly used state or behaviorNot possible with code-behindMuch cleaner designTake the time to setup MVVM itll be worth itUse or build a framework at minimum, a base layerFinalizerLet your ViewModel evolve naturallyThink about ViewModel inheritance where applicableDont concentrate on code-behind eliminationIt will happen naturally and eventuallyIn most cases, you may start out never using code-behindDont forget your unit testsShould have one unit test per-ViewModelReferencesJosh Smiths 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 exerciseTONS of MVVM stuff on the webDEV Track Resourceshttp://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

Resourceswww.microsoft.com/techedSessions On-Demand & Community

Microsoft Certification & Training ResourcesResources for IT ProfessionalsResources for Developerswww.microsoft.com/learning http://microsoft.com/technet http://microsoft.com/msdn

Learninghttp://northamerica.msteched.comConnect. Share. Discuss.

31Tech Ed North America 20105/19/2011 6:06 PM 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Complete an evaluation on CommNet and enter to win!

32Tech Ed North America 20105/19/2011 6:06 PM 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Scan the Tag to evaluate this session now on myTechEd Mobile33Tech Ed North America 20105/19/2011 6:06 PM 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Thank You For Attending !Miguel A. Castro

miguel.castro@idesign.net@miguelcastro67www.dotnetdude.comStay in touch

35