Date post: | 02-Apr-2018 |
Category: |
Documents |
Upload: | edmundo-lozada |
View: | 217 times |
Download: | 0 times |
of 35
7/27/2019 03_MVVM.pdf
1/35
03 | Model-View-ViewModel
Ben Rigahttp://about.me/ben.riga
7/27/2019 03_MVVM.pdf
2/35
Building Apps for Both Windows 8 and Windows Phone 8 Jump Start01 | Comparing Windows 8 and Windows Phone 8
02 | Basics of View Models
03 | MVVM ( (Model-View-ViewModel)
04 | Sharing Code
Course Topics
7/27/2019 03_MVVM.pdf
3/35
Model-View-ViewModel
7/27/2019 03_MVVM.pdf
4/35
Introduction to MVVM (Model-View-ViewModel)Architecture
Pros and cons
Sharing code using MVVM
.NET portable class library
Best practices
Agenda
MVVM libraries
MVVM Light Toolkit
Q&A
7/27/2019 03_MVVM.pdf
5/35
Introduction to MVV
7/27/2019 03_MVVM.pdf
6/35
MVVM is a software architectural pattern
Like many patterns, it promotes code reuse through separations of concerns and modu
An MVVM app is divided into three main parts:
The Model stores and maintains the program data
The View presents data and receives user-input through a platform-customized UI and
The ViewModel presents an interface to bind data to Views
Each part is very loosely coupled
Reuse the Model and the ViewModel across platforms, but not the View
Architecture Overview: What is MVV
7/27/2019 03_MVVM.pdf
7/35
Architecture
View
ViewModel
CommandsDataBinding
Events/Messages
View
View
Messages,Callbacks
Model
7/27/2019 03_MVVM.pdf
8/35
Not every app should use MVVM
Weigh the pros and cons and decide the best approach for your scenario
Pros and Cons
Pros
Can reuse Model and View-Model code acrossplatforms
Code has a clearly defined structure
Test the ViewModel with unit tests
Maintainability
Can show design-time data in Expression Blendand the Visual Studio designer
Cons
Lots of boilerplate code
May be more powerful than necapps
Decoupling loses strong type ch
7/27/2019 03_MVVM.pdf
9/35
Sharing Code using
MVVM
7/27/2019 03_MVVM.pdf
10/35
This section looks at some of the details of MVVM
Also, a look at the portable class library
Finally, some best practices when using MVVM
Includes an overview of each part of MVVM
Model, View, and ViewModel
Emphasis on those parts that facilitate code sharingData Binding
Commands
Messages
MVVM and Code Sharing
7/27/2019 03_MVVM.pdf
11/35
The Model, or the Data Model, stores the persistent dappCan be databases, local storage files, settings, or any other persistent data
Responsible for create, retrieve, update, and delete operations
Model should know nothing about the View or ViewM
Usually the most portable part of the app
Windows Phone 8 supports a local SQL Server CE dat
Windows 8 does not, but SQLite libraries are readily available
Model
7/27/2019 03_MVVM.pdf
12/35
ModelpublicclassCommonDataItem
{
public DataItem(string uid)
{
Uid = uid;
}
publicstring Uid
{
get;
privateset;}
// Other properties ...
}
publicinterfaceIDataService {
void GetItem(Action
7/27/2019 03_MVVM.pdf
13/35
A View should present the user with an interface to semanipulate the dataAn app can have many Views
Views are defined by XAML
Data binding connects Views to ViewModels
Still possible to manually listen for changes and update the Views and the Model from t
- Not the best way to keep a View up-to-date
In MVVM, the View does not handle user actionsThat is the responsibility of the ViewModel
View
7/27/2019 03_MVVM.pdf
14/35
A ViewModel, or PresentationModel, is responsible foPresenting data to the view
Responding to user manipulations of the view
Data binding can relieve the work of updating the view
The ViewModel holds the business logicof the appDecoupled from the View
Lets developers work on the ViewModel while designers work on the View
ViewModel
7/27/2019 03_MVVM.pdf
15/35
An app can have many ViewModels
Usually a one-to-one correspondence between Views ViewModels
A ViewModel is linked to a View by setting the DataCoproperty for an element in the ViewThis binding is inherited by all child elements
ViewModel
7/27/2019 03_MVVM.pdf
16/35
ViewModelpublicclassMainViewModel : ViewModelBase
{
privatereadonlyIDataService _dataService;
publicconststring Title_PropertyName = "Title";privatestring _title = string.Empty;
publicstring Title
{
get { return _title; }
set
{
if (_title == value)
return;
_title = value;
RaisePropertyChanged(Title_PropertyName);
}
}
// Constructor...
}
public MainViewModel(IDataSe
{
_dataService = dataServi
_dataService.GetData(
(item) =>
{
Title = item.Tit
});
}
7/27/2019 03_MVVM.pdf
17/35
The demo for this presentation uses the PhotoManageIt showcases MVVM well.
The PhotoManager will also be used for demos in the next presentation.
About the Demo
Shared
PhotoManager.Core.Win8 PhotoManager.Core.WP8
PhotoManager.WP8PhotoManager.Win8
7/27/2019 03_MVVM.pdf
18/35
Demo: MVVM
7/27/2019 03_MVVM.pdf
19/35
Data binding is critical to the MVVM patternLinks the View to the ViewModel
Can be a one-time, one-way, or two-way link
Advantages:
Write less code to update the view
Easier to unit test
Loose coupling avoids crashing the app
Can provide design-time data for the designer
Data Binding
7/27/2019 03_MVVM.pdf
20/35
In MVVM, commands let the View tell the ViewModel code in response to a user action
Replaces the paradigm of registering for events in the View.
Implement System.Windows.Input.ICommand interface
Commands can be enabled and disabled
-Raise the CanExecuteChanged event when this happens
Commands
7/27/2019 03_MVVM.pdf
21/35
In the XAML snippet, make suDataContext isset to an inst
ViewModel class.
The ViewModel class exposeAddCommand property of tyAddItemCommand
The ViewModel is responsibadding a new item
Commands
7/27/2019 03_MVVM.pdf
22/35
Messages are a way to send information between obje
Sender and receiver
Useful for communication between ViewModels
Often a callback for when the receiver is done handling a message
No built-in APIs, but some MVVM libraries provide support
Why send messages?Suppose two ViewModels are attached to a single view
- Each ViewModel handles a part of the view
You want actions received by one ViewModel to be passed to another
Messages
7/27/2019 03_MVVM.pdf
23/35
MessagespublicinterfaceIMesseng
{
void
Subscribe(Actio
handler);
void
Unsubscribe(Act
handler);
void Publish
7/27/2019 03_MVVM.pdf
24/35
MessagespublicclassMessageRecipient{
public MessageRecipient(){
Messenger.Default.Register(this, async (msg) =>{
var dlg = newMessageDialog(msg.Content);await dlg.ShowAsync();
});}
}
publicclassMyMes
{publicstring
{get;set;
}}
var _recipient = newMessageRecipient();// ...Messenger.Default.Send(newMyMessage() { Content = "Hello World!" });
7/27/2019 03_MVVM.pdf
25/35
Visual Studio 2012provides a portableclass library template
Only cross-platform .NET APIs available
Compiles into a separate library (.dll)
Only managed code
Only available in non-express editionsof Visual Studio 2012
.NET Portable Class Library
7/27/2019 03_MVVM.pdf
26/35
Design apps for cross-platform portability
Use MVVM to help achieve this
Keep the components of an app loosely coupled
Separation of concerns
- Each component has a single well-defined role
Avoid dependencies between Model, View, ViewModel
Plan for upgrades, redesigns, and testing
Again, consider MVVM or another loosely coupled architecture
Best Practices
7/27/2019 03_MVVM.pdf
27/35
Data binding should eliminate a lot of the code in the
behind fileSome code-behind is OK, but look for ways to use data-binding and commands to repla
Avoid binding the same large collection multiple timessame XAML page
This applies to pivots as well. Avoid duplicate bindings to different pivot pages that are pivot.
Binding does incur both memory and CPU overhead, careful how much data is bound to a page.
Best Practices
7/27/2019 03_MVVM.pdf
28/35
Large collections bound to list controls should be virtu
You can use the VirtualizingStackPanel in place of the StackPanel
You can narrow the scope of the bindings data contexthe XAML document. For example:
A Car object exposes an Engine object through a property named CarEngine
A Car exposed by the MyCar property (of the View Model) is the data context for a XA
Child elements of that XAML element can change their data context to the CarEngine byMyCar.CarEngine.
This helps avoid long property paths.
Best Practices
7/27/2019 03_MVVM.pdf
29/35
MVVM Libraries
7/27/2019 03_MVVM.pdf
30/35
Numerous Tools Available
Sou
7/27/2019 03_MVVM.pdf
31/35
Open-source framework created and maintained by G
Library includes Visual Studio templates
Download at: http://mvvmlight.codeplex.com/
Supports a light-weight implementation of the MVVM
Suitable for medium-large projects
Two parts to the library
Essentials: RelayCommand, Messenger, ViewModelBase
Extras: EventToCommand, DispatcherHelper
MVVM Light Toolkit
http://mvvmlight.codeplex.com/http://mvvmlight.codeplex.com/http://mvvmlight.codeplex.com/7/27/2019 03_MVVM.pdf
32/35
Recap
7/27/2019 03_MVVM.pdf
33/35
MVVM means Model-View-ViewModel
The Model stores the persistent data
The View presents the user with an interface to view and manipulate data
A ViewModel presents data to the view and responds to user actions
MVVM is a useful pattern for Windows Phone 8 (and W
8) that lets you reuse much of your app business logicAvoid causing chaos in the ViewModel when you replace the View
MVVM works well with other cross-platform code reusstrategies:
Portable libraries, inheritance, partial classes, shared code files, #if blocks
Recap
7/27/2019 03_MVVM.pdf
34/35
Q&A
7/27/2019 03_MVVM.pdf
35/35