27
Build For Both MVVM for Portability Badreddine Kedjour b- [email protected] Microsoft Develope r and Platform Evangeli sm

Imagine Camp Algeria 2014 Build for both session2 mvvm

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Imagine Camp Algeria 2014 Build for both session2 mvvm

Build For BothMVVM for Portability

Badreddine [email protected]

Developerand PlatformEvangelism

Page 2: Imagine Camp Algeria 2014 Build for both session2 mvvm

What is MVVM?

Model

View (XAML)

ViewModel

Design/Development Separation

Code Reuse

Multiple Views On the Same Logic

View-Logic Testability

Page 3: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 4: Imagine Camp Algeria 2014 Build for both session2 mvvm

ViewModel - C#

INotifyPropertyChanged

View - XAML

Text=“{Binding MyProperty}”

View (XAML)

ViewModel

Data Bindings

DataBinding

Page 5: Imagine Camp Algeria 2014 Build for both session2 mvvm

Data Binding

Page 6: Imagine Camp Algeria 2014 Build for both session2 mvvm

Data Binding Basics

XAML Binding Options

Binding with ViewModels

Data Binding

Page 7: Imagine Camp Algeria 2014 Build for both session2 mvvm

Data Binding Basics

XAML Binding Options

Binding with ViewModels

Data Binding

Page 8: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 9: Imagine Camp Algeria 2014 Build for both session2 mvvm

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)

Page 10: Imagine Camp Algeria 2014 Build for both session2 mvvm

Data Binding Basics

XAML Binding Options

Binding with ViewModels

Data Binding

Page 11: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 12: Imagine Camp Algeria 2014 Build for both session2 mvvm

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}}" />

Page 13: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 14: Imagine Camp Algeria 2014 Build for both session2 mvvm

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\}’}“ />

Page 15: Imagine Camp Algeria 2014 Build for both session2 mvvm

Data Binding Basics

XAML Binding Options

Binding with ViewModels

Data Binding

Page 16: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 17: Imagine Camp Algeria 2014 Build for both session2 mvvm

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)); } }}

Page 18: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 19: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 20: Imagine Camp Algeria 2014 Build for both session2 mvvm

ViewModel - C#ICommand

DelegateCommand

RelayCommand

View XAMLCommand=“{Binding MyCommand}”

View (XAML)

ViewModel

Commands

Commands

Page 21: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 22: Imagine Camp Algeria 2014 Build for both session2 mvvm

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;}

Page 23: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 24: Imagine Camp Algeria 2014 Build for both session2 mvvm

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"); }}

Page 25: Imagine Camp Algeria 2014 Build for both session2 mvvm

MVVM and Code Sharing

Page 26: Imagine Camp Algeria 2014 Build for both session2 mvvm

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

Page 27: Imagine Camp Algeria 2014 Build for both session2 mvvm

© 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.