Download presentation
Presentation is loading. Please wait.
Published byVivien Wade Modified over 8 years ago
1
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th 2012 www.snowball.be - gill.cleeren@ordina.be - @gillcleeren
2
Agenda Core concepts – Data binding in Windows 8 – Data templates – INotifyPropertyChanged & INotifyCollectionChanged The MVVM pattern – What is MVVM – Why and why not MVVM – Parts of MVVM MVVM Light introduction Linking view and viewmodel Commanding – EventToCommand? Messaging Navigation and other servicing Contracts and MVVM
3
CORE CONCEPTS
4
DATABINDING
5
Data binding explained Data + binding Data: properties of objects or collections thereof Binding: linking these to properties of controls Infrastructure for binding control properties to objects and collections “ Loosely coupled model Bound control doesn’t need to know to what is being bound to Databinding exists in Silverlight WPF ASP.NET Windows Forms Windows 8 5
6
Data binding explained A binding is defined by 4 items: Source object Source property Target object (must be dependency object) Target property (must be dependency property) Data binding works on in-memory data Coming from a service possibly 6
7
Data binding What is supported in Windows 8? – Regular data binding – Element binding – Converters – Model binding – Indexers – Data templating – Binding to a CollectionViewSource – Notifications Single objects Collections – Binding to JSON collections WCF service – Exceptions in output window
8
That means... No StringFormat, FallbackValue,... No custom markup extensions No implicit data templates No data binding breakpoints... More or less at the level of Silverlight 3
9
SIMPLE DATA BINDING DEMO
10
Data templates Block of XAML that is generated for each item of the source list Mostly used on List controls such as the GridView or ListView Uses regular data binding syntax – Source for binding is the individual item Windows 8 doesn’t know – AncestorType/AncestorLevel for RelativeSource Binding – Implicit data templates
11
DATA TEMPLATES DEMO
12
INotifyPropertyChanged Synchronization doesn’t work automagically! Source needs to implement INotifyPropertyChanged If so, source update will result in target update TwoWay enables bidirectional flow of data 12 namespace System.ComponentModel { // Summary: // Notifies clients that a property value has changed. public interface INotifyPropertyChanged { // Summary: // Occurs when a property value changes. event PropertyChangedEventHandler PropertyChanged; }
13
INotifyPropertyChanged PropertyChanged is to be raised when value of the property changes Only works when binding is set to OneWay or TwoWay Won’t work if binding is set to OneTime Windows 8 checks item being bound If it implements the interface, it will start listening for events and update UI accordingly If not, it will not react to eventual changes of the source 13
14
INotifyCollectionChanged Also exists for collections in form of INotifyCollectionChanged interface ObservableCollection already implements this Update will only show updates of collection, not indivual items Sync therefore does not work on List ObservableVector also works This is a specific WinRT type 14
15
INOTIFYPROPERTYCHANGED AND INOTIFYCOLLECTIONCHANGED DEMO
16
THE MVVM PATTERN
17
What is MVVM? MVVM : – is an architectural pattern created by John Gossman from WPF team – is a variation of MVC pattern – is similar to Martin Fowler’s PresentationModel pattern – works because of XAML data Binding & commanding
18
What is MVVM?
19
Understanding MVVM V is part for the designer M is for the developer VM glues both these objects together – V can bind to properties of VM – VM remodels data so it is usable for the V
20
Why MVVM Better SoC (Seperation of Concerns) More maintainable – Model never needs to be changed to support changes to the view – ViewModel rarely needs to be changed to support changes to the view – Code is easier to find More testable – ViewModel is easier to unit test than code-behind or event driven code Eliminates the need to do code behind which leaves the UI all in XAML Because the framework have the power to support it – Databinding/DataContext/Observable pattern
21
Why not MVVM Lack of standardization so everyone has own favor Windows 8 Grid template has its own “MVVM” model Message to community is not clear!! For simple UI, M-V-VM can be overkill Too much code needed – INotifyPropertyChanged – Commands
22
Everything in code-behind Data Model View XAML Code-Behind Event Handlers
23
Model – View – ViewModel Data Model View XAML Code-Behind View Model State + Operations Change notification Data-binding and commands
24
The parts of MVVM View knows ViewModel ViewModel knows Models But not vice versa. ViewViewModelModel
25
The View The view – represents the user interface that the user will see. – can be a user control or Data Template – shouldn't contain any logic that you want to test – should be kept as simple as possible.
26
The ViewModel An abstraction of View Connector between View and Model Keep View State, Value Conversion No strong or weak (via Interface) reference of View Make VM as testable as possible (e.g. no call to Singleton class) No Control related Stuff in VM
27
The Model Can be Data Model, DTO, POCO, auto- generated proxy of domain class and UI Model based on how you want to have the separation between Domain Service and Presentation Layer No reference to ViewModel
28
MVVM LIGHT INTRODUCTION
29
MVVM Light Open-source project by Laurent Bugnion – http://mvvmlight.codeplex.com/ http://mvvmlight.codeplex.com/ Light-weight, base classes for MVVM implementation – Not a real framework – Contains base implementation for ViewModel, Messaging, Locator…
30
Most important classes of MVVM Light ViewModel – ViewModelBase Commands – RelayCommand – EventToCommand Messaging – Messenger – Several types of messages IOC – SimpleIOC
31
LOOKING AT A SAMPLE MVVM IMPLEMENTATION DEMO
32
Linking the View and the ViewModel A view needs to “find” its ViewModel – ViewModel is the DataContext 2 options: – View First – ViewModel First
33
Locator pattern Implemented through a class that contains all VMs as properties An instance is then made available as Resource All Views can bind, no code needed in View – Clean way – Not good since all VMs need to be known upfront Property for each available VM Not easy if more than one instance exists of a View – In this case, some form of IOC is recommended
34
THE LOCATOR PATTERN DEMO
35
COMMANDING
36
Commands MVVM-based code have no event handlers in code-behind How to handle events happening in the UI? Commands WinRT has the ICommand interface – Execute() – CanExecute() – CanExecuteChanged event
37
Commands Way to create commands: – Write ICommand implementation – Create instance on VM – Bind Command property of control to this instance Works only on some controls For others, we need to use EventToCommand class – Allows linking of an event with a Command on the ViewModel – … Oops, it’s not available in WinRT!!!!
38
Using EventToCommand as a behavior Take a look at WinRTBehaviors on CodePlex <Button x:Name="btnSubmit" Content="Submit" FontFamily="{StaticResource MyFont}" FontSize="{StaticResource MyFontSize}" HorizontalAlignment="Center" Margin="0,20,0,0"> <Win8nl_Behavior:EventToCommandBehavior Event="Tapped" Command="AreYouSureCommand" CommandParameter="{Binding MyName}"/>
39
COMMANDING DEMO
40
MESSAGING
41
Communication between VMs View Model
42
Messaging Data Model View XAML Code- Behind Data Model View XAML Code- Behind Message View Model State + Operations View Model State + Operations View XAML Code- Behind Message Event Aggregator View Model State + Operations Publish messages Subscribe to messages
43
Communication between VMs VM’s need to be able to talk to each other, eg: send messages to each other – Not a good idea to have each VM reference all other VMs Solution: – Event Aggregator/mediator/messenger – VM can register to receive messages of a certain type (for example string messages) – Another VM can register with the same messenger to send messages – This allows both VMs to communicate with each other without tight coupling
44
MESSAGING DEMO
45
NAVIGATION, DIALOGS AND OTHER SERVICING
46
External servicing Many tasks remain open – Don’t belong in View – Don’t belong in ViewModel If this is the case, they should be an separate service – Navigation – Showing a dialog, error… – Loading data into the model – …
47
External servicing An external service is nothing more than a class that does ONE specific job – Remember the SOC principle An instance of these classes is often created application-wide – An IOC is recommended for this task
48
NAVIGATION, DIALOGS AND OTHER SERVICING DEMO
49
WINDOWS 8 SPECIFICS
50
Contracts Sharing – Allows apps to share information with other apps – Mediator pattern Search – Creates a unified way of searching in the content of the app
51
Contracts in MVVM Using contracts from MVVM – Service-type solution – Event-based model – Works by calling from ViewModel without problems
52
ADDING THE SHARE CONTRACT USING MVVM DEMO
53
Summary MVVM allows us to build more maintainable Windows 8 apps Not very different from MVVM in Silverlight, WP7 or WPF MVVM Light is a solid base
54
THANKS!
55
Q&A
56
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th 2012 www.snowball.be - gill.cleeren@ordina.be - @gillcleeren
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.