training: mvvm pattern
DESCRIPTION
The Model View ViewModel (MVVM) is an architectural pattern originated by Microsoft as a specialization of the Presentation Model (Martin Fowler). Similar to MVC, MVVM is suitable for client applications (Xaml-based, Xamarin, SPA, ...) because it facilitates a clear separation between the UI and the Business Logic. Examples with WPF, MvvmCross, AngularJs. It also contains solutions for common use cases.TRANSCRIPT
MVVM PATTERNUNDER THE SCOPE
MAXIME LEMAITRE
Agenda
• Brief History• Overview• A First example• Where magic happens …• Common scenarios• Conclusion• Questions
Many examples in WPF, but many concepts also apply to the others stacks
Brief History
• Originated from Microsoft – inspired from Presentation Model design pattern introduced by Martin Fowler– First article in 2005 by John Gossman – Standardization by Josh Smith in 2009
• Originally invented in WPF– But later adopted in Silverlight, Windows Phone, Windows 8
• Now– Favorite pattern for all Xaml-based application (WPF, Win8, WP, …) and
Xamarin apps– … Also in Java (ZK) …– … and for the Web (AngularJS, KnockoutJS, …)
Architectural View
• The Model includes all the code that implements the core app logic and defines the types required to model the app domain. This layer is completely independent of the view and view model layers.
• The View layer defines the UI using declarative markup. Data binding markup defines the connection between specific UI components and various ViewModels (and sometimes model) members.
• The ViewModel layer provides data binding targets for the view. In many cases, the view model exposes the model directly, or provides members that wrap specific model members. The view model can also define members for keeping track of data that is relevant to the UI but not to the model, such as the display order of a list of items.
MVVM Compared to others Patterns
ViewModel in MVC (aka Presentation.Model) is very different in MVVM !
Why MVVM ?
• Loosely coupled architecture. The MVVM pattern promotes a design pattern that emphasizes the separation of concerns between view, user interaction logic, behaviors and model. Applications built with such loosely coupled architecture often result in rock-solid stability with less issues.
• Maintainable and extensible code. With MVVM pattern, your code is more maintainable and easy to extend. This is made possible because your project is generally separated into layers thus enables you to enhance specific parts without affecting the others.
• Testable code. The MVVM pattern allows your code to be consistently tested through unit testing. It is possible to unit test only certain functions in the layers, thanks to the great separation concept introduced by MVVM.
• Manageable development process. With the UI (View) separated from the user interaction logic, designers can focus on the user interface and experience aspects of the application, while developers can focus on the model, entities and business logic in a parallel work stream.
Dream WorldDesigner-Programmer workflow
Clear Responsibilities between Designers and Developers.
What about AngularJS ?https://plus.google.com/+AngularJS/posts/aZNVhj355G2
“For several years AngularJS was closer to MVC … but over time and thanks to many refactorings and api improvements, it's now closer to MVVM ”
“Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for whatever works for you".
A quick examplewithout MVVM, WinForms-like
Each control should have a name to be used in CodeBehind
You have to assign a method to an event handler to process UI action.
A quick examplewithout Model, just VVM
No codebehind !
A quick examplewith AngularJS
Model/properties don’t need to observable..
“Knockout dependency tracking is a clever feature for a problem which angular does not have” –StackOverflow
the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller
Mvvm Concepts
• DataContext • Data Binding• INotifyPropertyChanged• Commands• Data Templates
DataContext
• Fundamental concepts in Data Binding (see next)– refers to a source of data that can be bound to a target
• All User interface elements in WPF have a DataContext dependency property• That property has "value inheritance", so if you set the DataContext on an element,
the DataContext property on all of its logical descendant elements will reference the same object too.
• The DataContext is set to a bindable entity– ViewModel in Mvvm
• Can be set via Code or via Markup
Data Binding
• Data binding connects two properties (called binding target property and binding source property), so that if one changes, the other changes too– The target property of a binding should always be a WPF dependency property – The source property of a binding should be either a dependency property or
fire PropertyChanged event on the property change.• Automated• Many options
– Direction of the data flow (One way, two way, One Time, One way to source, …)– What triggers source updates (LostFocus, PropertyChanged, Explicit, …)– Bind to objects, collections, UI Elements,– Path, Value Converters, Async, Fallback, StringFormat … – Continue Reading here
• MVVM– Databing push the changes to from ViewModel to View and From View To ViewModel– Think Data binding : everything should be data bound !
INotifyPropertyChanged
"Is it generally desirable to implement INotifyPropertyChanged on Model classes, ViewModel classes, or both?” Answer here
Also for INotifyCollectionChanged, IDataErrorInfo, INotifyDataErrorInfo
No INotifyPropertyChanged = No Databinding !
used to notify clients, typically binding clients, that a property value has changed.
Commands
• Invoked in the View by user interaction.– encourages a clean Xaml/UI
• Bound to ICommand properties in the ViewModel• All MVVM-Frameworks provide implementations for ICommand
– RelayCommand– EventToCommand
Data Templates
• Converts non-visual data into its visual representation• Defines how a view model will be rendered or can modify its default visual
representation without changing the underlying object itself or the behavior of the control that is used to display it.
Simple DataTemplate for a ListBoxItem
More advanced DataTemplate for a DataType
Popular .NET MVVM Frameworks
MVVM is an architectural pattern : it’s not standardized by MS or mandatory (such as in asp.net MVC). Many developers has already created very good implementations.
• MVVM Light Toolkit• Caliburn.Micro• MvvmCross• Catel• Simple MVVM Toolkit• Cinch• …• …• Your own here
Not all Frameworks are portable (PCL) !
Use case #1List with Selection
How to get the selected item of a list without adding an handler to the selected event ? (Because we don’t want something in code behind files)
Bind the SelectecItem to the CurrentXXX property of the ViewModel : each time an item is selected, the CurrentXXX will be updated automatically
Use case #2VM-VM communications
Use a messenger (Mediator pattern) to send/receive notifications + parameters.
Useful for master/child, splash screens, progress bar, dialogs, …
How to communicate between ViewModels ? (because a ViewModel should ideally have no knowledge of views or even the others VMs)
Use case #3Formatting & Data conversion
Should I have to add a property to a View Model to display YYY when my model property is in format XXX ?
Use a Value Converter !
Use case #4Load Data
How/when do I load data in a Mvvm app ?
Async all the way ! Never block UI thread in Client App Dev.App taking more than 5 seconds are often killed by Os.When loading data, working on rendering thread may freeze animation & UX
Common scenarios #5show/navigate between views
How do I navigate between view in a Mvvm app ?
Using MvvmCrossCustom implementation
It depends on the navigation logic : master-detail, tabs, modal, … Use the native platform NaviguationService or a custom implementation of your favorite MVVM Framework.
Common scenarios #6show Modal Dialog
How do I show dialog messages/custom views ?
Send dialog messages with Messenger (VM->View communication)Even better create a dialog service to fit your context (Custom View, Async, callback, …)
Questions
References
• http://technology4excellence.wordpress.com/2014/04/07/mvc-mvp-mvvm/• http://msdn.microsoft.com/en-us/library/gg405484.aspx• http://www.intersoftpt.com/Support/ClientUI/Documentation/MVVMPatternOverview.html • http://stackoverflow.com/questions/13156040/nice-and-simple-definition-of-wpfs-mvvm • http://www.codeproject.com/Articles/278901/MVVM-Pattern-Made-Simple• http://www.slideshare.net/Jaffel/introduction-to-design-pattern-mvvm• http://www.codeproject.com/Articles/100175/Model-View-ViewModel-MVVM-Explained • http://www.codeproject.com/Articles/278901/MVVM-Pattern-Made-Simple • http://msdn.microsoft.com/en-us/magazine/jj651572.aspx
We want our Sports betting, Poker, Horse racing and Casino & Games brands to be easy to use for every gamer around the world. Code with us to make that happen.
Look at all the challenges we offer HERE
We’re hiring !
Check our Employer Page
Follow us on LinkedIn
About Us• Betclic Everest Group, one of the world leaders in online
gaming, has a unique portfolio comprising various complementary international brands: Betclic, Everest, Bet-at-home.com, Expekt, Monte-Carlo Casino…
• Through our brands, Betclic Everest Group places expertise, technological know-how and security at the heart of our strategy to deliver an on-line gaming offer attuned to the passion of our players. We want our brands to be easy to use for every gamer around the world. We’re building our company to make that happen.
• Active in 100 countries with more than 12 million customers worldwide, the Group is committed to promoting secure and responsible gaming and is a member of several international professional associations including the EGBA (European Gaming and Betting Association) and the ESSA (European Sports Security Association).