View
133
Download
3
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
What is MVVM?
Model
View (XAML)
ViewModel
Design/Development Separation
Code Reuse
Multiple Views On the Same Logic
View-Logic Testability
MVVM Overview
Model
View (XAML)
ViewModel
Data Bindings Command
s
ModelSimple representation of dataNo logic or functionality
ViewModelApplication logicService callsData management
ViewUser InterfaceNavigate to viewsInteraction layer
ViewModel - C#
INotifyPropertyChanged
View - XAML
Text=“{Binding MyProperty}”
View (XAML)
ViewModel
Data Bindings
DataBinding
Data Binding
Data Binding Basics
XAML Binding Options
Binding with ViewModels
Data Binding
Data Binding Basics
XAML Binding Options
Binding with ViewModels
Data Binding
Data binding in three parts
1. Binding source: object with data that you want to present (View Model)
2. Binding target: DependencyProperty of a FrameworkElement
3. Binding object: sync data between the source and target, possibly reformatting it with a value converter
Data Binding Basics
Binding engine gets info from the Binding object: Source and target objects Direction of the data flow (Binding.Mode property) Optionally, a value converter (Converter property)
Data Binding Architecture
Binding Target
(Property)
Binding Source (DependecyProperty /
INotifyPropertyChanged
)
Binding Object
Data Updates (one-way)
Data Updates (two-way)
Data Updates (one-way)
Data Updates (two-way)
Data Binding Basics
XAML Binding Options
Binding with ViewModels
Data Binding
A DependencyProperty is a special type of property Can be data bound Tracked by XAML Binding Engine For data binding to work, the object with the dependency property must be a subclass of DependencyObject
Dependency Property, Dependency Object
<TextBlock x:Name="DescriptionTextBlock" Margin="12,0,0,0" Text="{Binding Description} " />
Dependency Property
Binding Markup Extension
Dependency Object
Converters - bind a target and a source that are different types For example: suppose you want to show an element only if a bool variable is true Provide a class that implements IValueConverter
Convert from the source type to the target typeConvertBack from the target type to the source type
Converters
<TextBlock x:Name="MyTextBlock" Visibility="{Binding IsVisibleBool, Converter={StaticResource BoolToVisibilityConverter}}" />
Binding Modes
<Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" />
OneTimePopulated with data only once, on page load
OneWayView changes to match data from ViewModel
TwoWayData linked in binding also changes in ViewModel as View updates
More advanced property paths Instead of just setting the source to a property of the data context object, you can chain together properties to dig into the object:
Use the StringFormat property to format text The property being bound should implement the IFormattable interface (DateTime in this example)
Other Binding Options
<Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" />
<TextBlock Text="{Binding Coupon.ExpirationDate, StringFormat=‘Expiration Date: \{0:d\}’}“ />
Data Binding Basics
XAML Binding Options
Binding with ViewModels
Data Binding
ViewModel acts as a binding source Properties exposed for binding Implements INotifyPropertyChanged, raises PropertyChanged event when a property is set Include business logic to respond to user actions in the view Persists data using a data service to save changes
Loosely coupled to a ViewAvoid direct references to individual XAML elements
View Model
View Model Examplepublic class ItemView Model : INotifyPropertyChanged{ private string _name; public string Name { get { return _name; } set { if (value != _name) { _name = value; NotifyPropertyChanged("Name"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } }}
OneWay or TwoWay binding must implement the INotifyPropertyChanged interface Fire PropertyChanged event whenever the value of a public property changes Runtime framework subscribes to this event, uses it to update bound UI elements One time binding does not require this
INotifyPropertyChanged
Two ways to bind collections of data: Extend ObservableCollection<T> Implement IList and INotifyCollectionChanged Items in the collection must implement INotifyPropertyChanged In the ItemsPanel of the XAML list element, you are bound to the individual item of the collection
Data Binding with Lists
ViewModel - C#ICommand
DelegateCommand
RelayCommand
View XAMLCommand=“{Binding MyCommand}”
View (XAML)
ViewModel
Commands
Commands
Expose a method like a propertyAttach commands to buttons and menu items Automatically executed by the system
View notifies the code that some action has occurred For example, when the user clicks a button, the app could clear a canvas or refresh data from a server
Implement the ICommand interface Execute: code that runs when the command is invoked CanExecute: called to check if the command is enabled CanExecuteChanged: raise this event when a command is enabled/disabled
Commands
Commands Example<Button Content="Say Hello" Command="{Binding HelloWorldCommand}"></Button>
class HelloWorldCommand : ICommand{ public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { MessageBox.Show("Hello world!"); }}
class MyView Model{ private HelloWorldCommand myCommand = new HelloWorldCommand(); public HelloWorldCommand HelloWorldCommand { get { return myCommand; } }}
protected override void OnNavigatedTo(NavigationEventArgs e){ DataContext = _myView Model;}
Reusable ICommand class No need to write a new class for each command Command acts as a pointer to ViewModel method
See Implementation At http://aka.ms/B4BDelegate
Delegate Commands
Delegate Command Examplepublic MyViewModel(){ loadSomeDataCommand = new DelegateCommand(LoadDataAction);}
private void LoadDataAction(object p){ // Load the data into the ObserverableCollection here}
// Command Propertyprivate ICommand loadSomeDataCommand;public ICommand LoadDataCommand{ get { return this.loadSomeDataCommand; }}
// Notify Propertyprivate ObservableCollection<ItemSummary> _dataSource = new ObservableCollection<ItemSummary>();public ObservableCollection<ItemSummary> DataSource{ get { return _dataSource; } set { _dataSource = value; NotifyPropertyChanged("DataSource"); }}
MVVM and Code Sharing
Build For Both MVVM Structure
Portable Class Libraries
Windows 8Windows Phone
8
Services
ViewModels
(limited/abstract)
Models
Commands
Interfaces
Views (XAML) App LifecycleNavigation
Views (XAML)Converters
Shared ViewModels (Add as Link)Storage, Alerts
View (XAML)
ViewModel
Model
© 2013 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.