SlideShare a Scribd company logo
1 of 32
Realizzare applicazioni cross-platform
con Xamarin e il pattern MVVM
Matteo Pagani
Windows AppConsult Engineer
Microsoft
ROME 18-19 MARCH 2016
matteo.pagani@microsoft.com
@qmatteoq
AGENDA
1. Xamarin
2. Il pattern MVVM
3. Xamarin & MVVM
4. Servizi & Dependency Injection
XAMARIN + MICROSOFT
XAMARIN
XAMARIN TRADIZIONALE
XAMARIN FORMS
IL PATTERN MODEL-VIEW-VIEWMODEL
• Aiuta lo sviluppatore a separare la logica dall’interfaccia
utente, migliorando la leggibilità, la testabilità e il design
del codice
• In ottica di sviluppo cross-platform, aiuta a massimizzare il
riutilizzo del codice su diverse piattaforme
• Il codice è suddiviso in tre layer differenti
• Nasce nel mondo delle tecnologie Microsoft, in quanto
sfrutta alcune delle principali feature dello XAML come il
data binding
IL PATTERN MVVM
DATA BINDING
• Permette di creare un canale per collegare due
proprietà di due oggetti: «source» e «target»
• La comunicazione può essere bidirezionale
• Nel pattern MVVM, il binding è utilizzato per
collegare i controlli nello XAML con le
proprietà di un ViewModel
<TextBlock Text="{Binding Path=Name}" />
DATACONTEXT
• Definisce il contesto a cui ogni controllo XAML può accedere
per sfruttare il binding.
• Il DataContext supporta l’ereditarietà.
• Nel pattern MVVM, il ViewModel viene definito come
DataContext dell’intera View: in questo modo, la View può
accedere a tutte le proprietà e comandi esposti dal
ViewModel.
<Page
x:Class="MVVMLight.Messages.Views.MainView"
DataContext="{Binding Source={StaticResource
MainViewModel}">
</Page>
INOTIFYPROPERTYCHANGED
• Come comportamento predefinito, una proprietà non è in
grado di far sapere al canale di binding che il suo valore è
cambiato
• Di conseguenza, i controlli non sono in grado di aggiornarsi in
automatico quando il valore della proprietà collegata cambia
• L’implementazione dell’interfaccia INotifyPropertyChanged
permette di gestire questo scenario
• Nel pattern MVVM, tutti i ViewModel implementano questa
interfaccia
INOTIFYPROPERTYCHANGED
Prima
public string Name { get; set; }
Dopo
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyOfPropertyChange(() => Name);
}
}
XAML
<TextBlock Text="{Binding Path=Name}" />
I COMMAND
• Solitamente le interazioni dell’utente sono gestite con gli event
handler, ovvero speciali metodi che sono collegati ad un
evento e che possono essere definiti solamente nel code
behind
• I command sono un modo per definire un’azione utilizzando
una proprietà e, di conseguenza, possono essere collegati da
un controllo tramite binding
• I command supportano la gestione dello stato (abilitato o
disabilitato), che si riflette automaticamente sulla UI del
controllo nell’interfaccia
I COMMAND
Codice
private ICommand _pinToStart;
public ICommand PinToStart
{
get
{
return _pinToStart
?? (_pinToStart = new RelayCommand(
() => taskService.PinToStart(CurrentItem),
() => canPin));
}
}
XAML
<Button Text="Pin to start" Command="{Binding Path=PinToStart}" />
DEMO
ROME 18-19 MARCH 2016
Il pattern MVVM
PROBLEMA
• Il pattern MVVM si basa su concetti, come il
binding, che sono specifici del mondo XAML
• Ci serve uno strumento per poter gestire il
binding anche su piattaforme differenti da
Windows
• Esistono diverse librerie che permettono di
aggiungere le funzionalità che ci servono
MVVM LIGHT
• Libreria open source creata da Laurent Bugnion, Microsoft
MVP e membro della .NET Foundation
• Compatibile con numerose tecnologie: WPF, Silverlight,
Universal Windows Platform, Xamarin Android e iOS
• Offre gli strumenti base per implementare il pattern:
• Classe base per i ViewModel
• Classe base per i Command
• Dependency injection e messaggi
http://www.mvvmlight.net/
MVVM CROSS
• Libreria open source disponibile su GitHub
• E’ un framework completo che, oltre a mettere a disposizione
gli strumenti base per implementare il MVVM, offre
funzionalità per risolvere scenari specifici delle varie
piattaforme
• Alcuni esempi:
• Dependency injection
• Gestione del ciclo di vita della pagina
• Navigazione
http://mvvmcross.com/
DEMO
ROME 18-19 MARCH 2016
MVVM e Xamarin
SERVIZI
• Per poter riutilizzare non solo la business logic ma anche i
ViewModel in ottica cross-platform, questi non dovrebbero
contenere alcun riferimento ad API specifiche di una
piattaforma
• Un ViewModel dovrebbe solamente descrivere le operazioni
da effettuare e le interazioni con l’utente, demandando ad
altre classi l’implementazione vera e propria
• Benvenuti servizi 
SERVIZI
public RelayCommand ShowDialogCommand
{
get
{
return new RelayCommand(async () =>
{
MessageDialog dialog = new MessageDialog("Hello world");
await dialog.ShowAsync();
});
}
}
Problema: questo command utilizza una API
specifica della Universal Windows Platform
SERVIZI
public interface IDialogService
{
Task ShowDialogAsync(string message);
}
I servizi vengono descritti da una interfaccia, che
descrive solamente le operazioni, e che viene
inclusa nel progetto condiviso
SERVIZI
L’implementazione vera e propria viene inclusa nel
progetto specifico per la piattaforma.
public class DialogService : IDialogService
{
public async Task ShowDialogAsync(string message)
{
MessageDialog dialog = new
MessageDialog(message);
await dialog.ShowAsync();
}
}
SERVIZI
Il ViewModel sfrutta l’interfaccia per invocare
l’operazione da eseguire:
public RelayCommand ShowDialogCommand
{
get
{
return new RelayCommand(async () =>
{
await _dialogService.ShowDialogAsync("Hello world");
});
}
}
PROBLEMA
Nell’approccio tradizionale, i servizi vengono
istanziati in fase di compilazione:
public MainViewModel MainViewModel
{
public MainViewModel()
{
DataService service = new DataService();
service.GetItems();
}
}
PROBLEMA
DataService service = new DataService();
service.GetItems();
DataService service = new DataService();
service.GetItems();
DataService service = new DataService();
service.GetItems();
DataService service = new DataService();
service.GetItems();
DEPENDENCY INJECTION
MainViewModel IDataService
public MainViewModel(IDataService dataService)
{
}
DataServiceTestDataService
LA SOLUZIONE
public ViewModel1(IDataService dataService)
public ViewModel2(IDataService dataService)
public ViewModel3(IDataService dataService)
public ViewModelN(IDataService dataService)
IDataService
DataServiceTestDataService
DEMO
ROME 18-19 MARCH 2016
Servizi e dependency injection
http://aka.ms/mvacs
CORSI MVA
C# Xamarin Forms
http://aka.ms/mvaforms
MATERIALE
https://github.com/qmatteoq/
Codemotion2016
DEMO
https://doc.co/ctc7Y2
SLIDE
Thanks!
ROME 18-19 MARCH 2016
Mail: matteo.pagani@microsoft.com
Twitter: @qmatteoq
All pictures belong
to their respective authors

More Related Content

What's hot

Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...
Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...
Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...Codemotion
 
Introduzione a jQuery
Introduzione a jQueryIntroduzione a jQuery
Introduzione a jQuerySandro Marcon
 
Generazione Dinamica di Codice in .NET
Generazione Dinamica di Codice in .NETGenerazione Dinamica di Codice in .NET
Generazione Dinamica di Codice in .NETStefano Ottaviani
 
Multi-Device Hybrid Apps con Visual Studio e Apache Cordova
Multi-Device Hybrid Apps con Visual Studio e Apache CordovaMulti-Device Hybrid Apps con Visual Studio e Apache Cordova
Multi-Device Hybrid Apps con Visual Studio e Apache CordovaAndrea Dottor
 
Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Manuel Scapolan
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012Andrea Dottor
 
Sviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailSviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailStefano Ottaviani
 
ASP.NET Core - Razor Pages
ASP.NET Core - Razor PagesASP.NET Core - Razor Pages
ASP.NET Core - Razor PagesAndrea Dottor
 
Training Signal Webtrends
Training Signal WebtrendsTraining Signal Webtrends
Training Signal WebtrendsStefano Iaboni
 
AntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreAntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreManuel Scapolan
 
Web Api – The HTTP Way
Web Api – The HTTP WayWeb Api – The HTTP Way
Web Api – The HTTP WayLuca Milan
 
ASP.NET MVC: sfruttare la piattaforma al 100%
ASP.NET MVC: sfruttare la piattaforma al 100%ASP.NET MVC: sfruttare la piattaforma al 100%
ASP.NET MVC: sfruttare la piattaforma al 100%DomusDotNet
 
Cosa c'è di nuovo in asp.net core 2 0
Cosa c'è di nuovo in asp.net core 2 0Cosa c'è di nuovo in asp.net core 2 0
Cosa c'è di nuovo in asp.net core 2 0Andrea Dottor
 
Progettare in Team per il Responsive Web Design
Progettare in Team per il Responsive Web DesignProgettare in Team per il Responsive Web Design
Progettare in Team per il Responsive Web DesignSalvatore Paone
 
Dal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersDal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersAndrea Dottor
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automationAntonio Liccardi
 
Alessandro Forte - MVP vs MVC
Alessandro Forte - MVP vs MVCAlessandro Forte - MVP vs MVC
Alessandro Forte - MVP vs MVCAlessandro Forte
 
Alessandro Forte - Realizzare controlli Ajax in ASP.Net
Alessandro Forte - Realizzare controlli Ajax in ASP.NetAlessandro Forte - Realizzare controlli Ajax in ASP.Net
Alessandro Forte - Realizzare controlli Ajax in ASP.NetAlessandro Forte
 

What's hot (20)

Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...
Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...
Xamarin.Forms Performance Tips & Tricks - Francesco Bonacci - Codemotion Rome...
 
Introduzione a jQuery
Introduzione a jQueryIntroduzione a jQuery
Introduzione a jQuery
 
Generazione Dinamica di Codice in .NET
Generazione Dinamica di Codice in .NETGenerazione Dinamica di Codice in .NET
Generazione Dinamica di Codice in .NET
 
Multi-Device Hybrid Apps con Visual Studio e Apache Cordova
Multi-Device Hybrid Apps con Visual Studio e Apache CordovaMulti-Device Hybrid Apps con Visual Studio e Apache Cordova
Multi-Device Hybrid Apps con Visual Studio e Apache Cordova
 
Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3Tutte le novità di ASP.NET MVC3
Tutte le novità di ASP.NET MVC3
 
Spa with Blazor
Spa with BlazorSpa with Blazor
Spa with Blazor
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012
 
Sviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailSviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRail
 
ASP.NET Core - Razor Pages
ASP.NET Core - Razor PagesASP.NET Core - Razor Pages
ASP.NET Core - Razor Pages
 
jQuery
jQueryjQuery
jQuery
 
Training Signal Webtrends
Training Signal WebtrendsTraining Signal Webtrends
Training Signal Webtrends
 
AntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatoreAntiPatterns: i vizi del programmatore
AntiPatterns: i vizi del programmatore
 
Web Api – The HTTP Way
Web Api – The HTTP WayWeb Api – The HTTP Way
Web Api – The HTTP Way
 
ASP.NET MVC: sfruttare la piattaforma al 100%
ASP.NET MVC: sfruttare la piattaforma al 100%ASP.NET MVC: sfruttare la piattaforma al 100%
ASP.NET MVC: sfruttare la piattaforma al 100%
 
Cosa c'è di nuovo in asp.net core 2 0
Cosa c'è di nuovo in asp.net core 2 0Cosa c'è di nuovo in asp.net core 2 0
Cosa c'è di nuovo in asp.net core 2 0
 
Progettare in Team per il Responsive Web Design
Progettare in Team per il Responsive Web DesignProgettare in Team per il Responsive Web Design
Progettare in Team per il Responsive Web Design
 
Dal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developersDal RenderFragment ai Generics, tips for Blazor developers
Dal RenderFragment ai Generics, tips for Blazor developers
 
Javascript task automation
Javascript task automationJavascript task automation
Javascript task automation
 
Alessandro Forte - MVP vs MVC
Alessandro Forte - MVP vs MVCAlessandro Forte - MVP vs MVC
Alessandro Forte - MVP vs MVC
 
Alessandro Forte - Realizzare controlli Ajax in ASP.Net
Alessandro Forte - Realizzare controlli Ajax in ASP.NetAlessandro Forte - Realizzare controlli Ajax in ASP.Net
Alessandro Forte - Realizzare controlli Ajax in ASP.Net
 

Similar to Realizzare applicazioni cross-platform con Xamarin e il pattern MVVM

Model-View-ViewModel con Windows Store Apps
Model-View-ViewModel con Windows Store AppsModel-View-ViewModel con Windows Store Apps
Model-View-ViewModel con Windows Store Appscodeblock
 
Designing with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDesigning with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDaniele Mondello
 
Asp.Net MVC 2 :: VS 2010 Community Tour
Asp.Net MVC 2 :: VS 2010 Community TourAsp.Net MVC 2 :: VS 2010 Community Tour
Asp.Net MVC 2 :: VS 2010 Community TourAndrea Balducci
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoMicrosoft Mobile Developer
 
MVVM senza fronzoli con Caliburn.Micro
MVVM senza fronzoli con Caliburn.MicroMVVM senza fronzoli con Caliburn.Micro
MVVM senza fronzoli con Caliburn.MicroMarco Amendola
 
MVVM Cross &lt;3 Xamarin
MVVM Cross &lt;3 XamarinMVVM Cross &lt;3 Xamarin
MVVM Cross &lt;3 XamarinCorrado Cavalli
 
Un backend per tutte le stagioni con Spring
Un backend per tutte le stagioni con SpringUn backend per tutte le stagioni con Spring
Un backend per tutte le stagioni con SpringMarcello Teodori
 
Migliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsMigliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsAndrea Dottor
 
Niccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTNiccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTfirenze-gtug
 
Unofficial Xamarin Day DomusDotNet
Unofficial Xamarin Day DomusDotNetUnofficial Xamarin Day DomusDotNet
Unofficial Xamarin Day DomusDotNetGaetano Paternò
 
e-SUAP - General software architecture (Italiano)
e-SUAP - General software architecture (Italiano)e-SUAP - General software architecture (Italiano)
e-SUAP - General software architecture (Italiano)Sabino Labarile
 
Yii Framework - yes it is rapid web application development (Parte 1)
Yii Framework - yes it is rapid web application development (Parte 1)Yii Framework - yes it is rapid web application development (Parte 1)
Yii Framework - yes it is rapid web application development (Parte 1)brossi676
 

Similar to Realizzare applicazioni cross-platform con Xamarin e il pattern MVVM (20)

Model-View-ViewModel con Windows Store Apps
Model-View-ViewModel con Windows Store AppsModel-View-ViewModel con Windows Store Apps
Model-View-ViewModel con Windows Store Apps
 
Designing with microservices - Daniele Mondello
Designing with microservices - Daniele MondelloDesigning with microservices - Daniele Mondello
Designing with microservices - Daniele Mondello
 
UI Composition
UI CompositionUI Composition
UI Composition
 
Asp.Net MVC 2 :: VS 2010 Community Tour
Asp.Net MVC 2 :: VS 2010 Community TourAsp.Net MVC 2 :: VS 2010 Community Tour
Asp.Net MVC 2 :: VS 2010 Community Tour
 
Mvvm
MvvmMvvm
Mvvm
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progetto
 
MVVM senza fronzoli con Caliburn.Micro
MVVM senza fronzoli con Caliburn.MicroMVVM senza fronzoli con Caliburn.Micro
MVVM senza fronzoli con Caliburn.Micro
 
MVVM Cross &lt;3 Xamarin
MVVM Cross &lt;3 XamarinMVVM Cross &lt;3 Xamarin
MVVM Cross &lt;3 Xamarin
 
Java lezione 14
Java lezione 14Java lezione 14
Java lezione 14
 
Spring e Flex
Spring e FlexSpring e Flex
Spring e Flex
 
Un backend per tutte le stagioni con Spring
Un backend per tutte le stagioni con SpringUn backend per tutte le stagioni con Spring
Un backend per tutte le stagioni con Spring
 
Migliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.jsMigliora il tuo codice con knockout.js
Migliora il tuo codice con knockout.js
 
Novità di Asp.Net 4.0
Novità di Asp.Net 4.0Novità di Asp.Net 4.0
Novità di Asp.Net 4.0
 
Niccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWTNiccolò Becchi: Introduzione a GWT
Niccolò Becchi: Introduzione a GWT
 
Unofficial Xamarin Day DomusDotNet
Unofficial Xamarin Day DomusDotNetUnofficial Xamarin Day DomusDotNet
Unofficial Xamarin Day DomusDotNet
 
MVC and Struts 1
MVC and Struts 1MVC and Struts 1
MVC and Struts 1
 
e-SUAP - General software architecture (Italiano)
e-SUAP - General software architecture (Italiano)e-SUAP - General software architecture (Italiano)
e-SUAP - General software architecture (Italiano)
 
m-v-vm @ UgiAlt.Net
m-v-vm @ UgiAlt.Netm-v-vm @ UgiAlt.Net
m-v-vm @ UgiAlt.Net
 
Hexagonal architecture ita
Hexagonal architecture itaHexagonal architecture ita
Hexagonal architecture ita
 
Yii Framework - yes it is rapid web application development (Parte 1)
Yii Framework - yes it is rapid web application development (Parte 1)Yii Framework - yes it is rapid web application development (Parte 1)
Yii Framework - yes it is rapid web application development (Parte 1)
 

More from Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

More from Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Realizzare applicazioni cross-platform con Xamarin e il pattern MVVM

  • 1. Realizzare applicazioni cross-platform con Xamarin e il pattern MVVM Matteo Pagani Windows AppConsult Engineer Microsoft ROME 18-19 MARCH 2016 matteo.pagani@microsoft.com @qmatteoq
  • 2. AGENDA 1. Xamarin 2. Il pattern MVVM 3. Xamarin & MVVM 4. Servizi & Dependency Injection
  • 7. IL PATTERN MODEL-VIEW-VIEWMODEL • Aiuta lo sviluppatore a separare la logica dall’interfaccia utente, migliorando la leggibilità, la testabilità e il design del codice • In ottica di sviluppo cross-platform, aiuta a massimizzare il riutilizzo del codice su diverse piattaforme • Il codice è suddiviso in tre layer differenti • Nasce nel mondo delle tecnologie Microsoft, in quanto sfrutta alcune delle principali feature dello XAML come il data binding
  • 9. DATA BINDING • Permette di creare un canale per collegare due proprietà di due oggetti: «source» e «target» • La comunicazione può essere bidirezionale • Nel pattern MVVM, il binding è utilizzato per collegare i controlli nello XAML con le proprietà di un ViewModel <TextBlock Text="{Binding Path=Name}" />
  • 10. DATACONTEXT • Definisce il contesto a cui ogni controllo XAML può accedere per sfruttare il binding. • Il DataContext supporta l’ereditarietà. • Nel pattern MVVM, il ViewModel viene definito come DataContext dell’intera View: in questo modo, la View può accedere a tutte le proprietà e comandi esposti dal ViewModel. <Page x:Class="MVVMLight.Messages.Views.MainView" DataContext="{Binding Source={StaticResource MainViewModel}"> </Page>
  • 11. INOTIFYPROPERTYCHANGED • Come comportamento predefinito, una proprietà non è in grado di far sapere al canale di binding che il suo valore è cambiato • Di conseguenza, i controlli non sono in grado di aggiornarsi in automatico quando il valore della proprietà collegata cambia • L’implementazione dell’interfaccia INotifyPropertyChanged permette di gestire questo scenario • Nel pattern MVVM, tutti i ViewModel implementano questa interfaccia
  • 12. INOTIFYPROPERTYCHANGED Prima public string Name { get; set; } Dopo private string name; public string Name { get { return name; } set { name = value; NotifyOfPropertyChange(() => Name); } } XAML <TextBlock Text="{Binding Path=Name}" />
  • 13. I COMMAND • Solitamente le interazioni dell’utente sono gestite con gli event handler, ovvero speciali metodi che sono collegati ad un evento e che possono essere definiti solamente nel code behind • I command sono un modo per definire un’azione utilizzando una proprietà e, di conseguenza, possono essere collegati da un controllo tramite binding • I command supportano la gestione dello stato (abilitato o disabilitato), che si riflette automaticamente sulla UI del controllo nell’interfaccia
  • 14. I COMMAND Codice private ICommand _pinToStart; public ICommand PinToStart { get { return _pinToStart ?? (_pinToStart = new RelayCommand( () => taskService.PinToStart(CurrentItem), () => canPin)); } } XAML <Button Text="Pin to start" Command="{Binding Path=PinToStart}" />
  • 15. DEMO ROME 18-19 MARCH 2016 Il pattern MVVM
  • 16. PROBLEMA • Il pattern MVVM si basa su concetti, come il binding, che sono specifici del mondo XAML • Ci serve uno strumento per poter gestire il binding anche su piattaforme differenti da Windows • Esistono diverse librerie che permettono di aggiungere le funzionalità che ci servono
  • 17. MVVM LIGHT • Libreria open source creata da Laurent Bugnion, Microsoft MVP e membro della .NET Foundation • Compatibile con numerose tecnologie: WPF, Silverlight, Universal Windows Platform, Xamarin Android e iOS • Offre gli strumenti base per implementare il pattern: • Classe base per i ViewModel • Classe base per i Command • Dependency injection e messaggi http://www.mvvmlight.net/
  • 18. MVVM CROSS • Libreria open source disponibile su GitHub • E’ un framework completo che, oltre a mettere a disposizione gli strumenti base per implementare il MVVM, offre funzionalità per risolvere scenari specifici delle varie piattaforme • Alcuni esempi: • Dependency injection • Gestione del ciclo di vita della pagina • Navigazione http://mvvmcross.com/
  • 19. DEMO ROME 18-19 MARCH 2016 MVVM e Xamarin
  • 20. SERVIZI • Per poter riutilizzare non solo la business logic ma anche i ViewModel in ottica cross-platform, questi non dovrebbero contenere alcun riferimento ad API specifiche di una piattaforma • Un ViewModel dovrebbe solamente descrivere le operazioni da effettuare e le interazioni con l’utente, demandando ad altre classi l’implementazione vera e propria • Benvenuti servizi 
  • 21. SERVIZI public RelayCommand ShowDialogCommand { get { return new RelayCommand(async () => { MessageDialog dialog = new MessageDialog("Hello world"); await dialog.ShowAsync(); }); } } Problema: questo command utilizza una API specifica della Universal Windows Platform
  • 22. SERVIZI public interface IDialogService { Task ShowDialogAsync(string message); } I servizi vengono descritti da una interfaccia, che descrive solamente le operazioni, e che viene inclusa nel progetto condiviso
  • 23. SERVIZI L’implementazione vera e propria viene inclusa nel progetto specifico per la piattaforma. public class DialogService : IDialogService { public async Task ShowDialogAsync(string message) { MessageDialog dialog = new MessageDialog(message); await dialog.ShowAsync(); } }
  • 24. SERVIZI Il ViewModel sfrutta l’interfaccia per invocare l’operazione da eseguire: public RelayCommand ShowDialogCommand { get { return new RelayCommand(async () => { await _dialogService.ShowDialogAsync("Hello world"); }); } }
  • 25. PROBLEMA Nell’approccio tradizionale, i servizi vengono istanziati in fase di compilazione: public MainViewModel MainViewModel { public MainViewModel() { DataService service = new DataService(); service.GetItems(); } }
  • 26. PROBLEMA DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems();
  • 27. DEPENDENCY INJECTION MainViewModel IDataService public MainViewModel(IDataService dataService) { } DataServiceTestDataService
  • 28. LA SOLUZIONE public ViewModel1(IDataService dataService) public ViewModel2(IDataService dataService) public ViewModel3(IDataService dataService) public ViewModelN(IDataService dataService) IDataService DataServiceTestDataService
  • 29. DEMO ROME 18-19 MARCH 2016 Servizi e dependency injection
  • 30. http://aka.ms/mvacs CORSI MVA C# Xamarin Forms http://aka.ms/mvaforms
  • 32. Thanks! ROME 18-19 MARCH 2016 Mail: matteo.pagani@microsoft.com Twitter: @qmatteoq All pictures belong to their respective authors