Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

.NET Fest 2017. Matteo Pagani. Prism and Xamarin Forms: create cross-platform applications using the MVVM pattern in a simpler way

158 views

Published on

The MVVM pattern is a widely used architectural patterns that makes easier for developers to separate the business logic of an application from the user interface, allowing to create applications that are easier to test and maintain over time. However, when it comes to create a new project, there are some challenges to face: we need to setup every time the required infrastructure, we need to understand how to handle scenarios that in an application written without using the pattern are apparently simpler to manage, etc. In this session we're going to see how Prism, an open source framework driven by the Community, can help to deliver better and faster a Xamarin Forms application built with the MVVM pattern, by allowing developers to focus on the core of the project rather than on the implementation of the pattern.

Published in: Education
  • Be the first to comment

  • Be the first to like this

.NET Fest 2017. Matteo Pagani. Prism and Xamarin Forms: create cross-platform applications using the MVVM pattern in a simpler way

  1. 1. Shared C# codebase • 100% native API access • High performance Shared C# Business Logic (Portable Class Library) Shared C# UI (XML) XAMARIN FORMS
  2. 2. <?xml version="1.0" encoding="UTF-8"?> <TabbedPage xmlns=“…" xmlns:x=“…“ x:Class="MyApp.MainPage" > > <TabbedPage.Children> <ContentPage Title="Profile" Icon ="Profile.png"> < <StackLayout Spacing="20" Padding="20” VerticalOptions="Center"> <<Entry Placeholder="Username" Text="{Binding Username}"> <<Entry Placeholder="Password” Text="{Binding Password}” IsPassword="true">> <<Button Text="Login" TextColor="White” BackgroundColor=”…” Command=”…">/> </<StackLayout>> </ContentPage>> <ContentPage Title = "Settings" Icon = "Settings.png">> <!-- Settings --> </ <ContentPage>> </TabbedPage.Children> </TabbedPage> XAMARIN FORMS
  3. 3. THE MVVM PATTERN
  4. 4. DATA BINDING  A channel to connect properties of two objects: a source and a target  The communication can be bidirectional  In MVVM, binding is used to connect the XAML controls with the ViewModel’s properties <TextBlock Text="{Binding Path=Name}" />
  5. 5. DATACONTEXT  It’s the context used by control to get access to the binding operation.  DataContext supports inheritance.  In the MVVM pattern, the ViewModel is defined as DataContext of the View: consequently, the View can access to all the commands and properties defined in the ViewModel.
  6. 6. INOTIFYPROPERTYCHANGED  It’s the interface that should be implemented by every class that interacts with the View.  It’s used to dispatch the changes from the code to the user interface.  ObservableCollection<T> is a special collection that implements the INotifyPropertyChanged interface, so that every change to the collection is dispatched to the user interface.
  7. 7. INOTIFYPROPERTYCHANGED Before public string Name { get; set; } After private string name; public string Name { get { return name; } set { name = value; NotifyOfPropertyChange (() => Name); } } XAML <TextBlock Text="{Binding Path=Name}" />
  8. 8. PRISM FOR XAMARIN FORMS • Prism was a MVVM framework originally created by the Patterns & Practises division by Microsoft • Now it’s an open source project driven by Brian Lagunas, a Microsoft MVP, and the community • It provides the basic infrastructure to implement the MVVM pattern: • Base class for ViewModels • Dependency injection container with multiple framework choices • Messages • It provides advanced features to solve specific requirements of Xamarin Forms: • Navigation from a ViewModel • Handling the page’s lifecycle • Handling platform specific code • Deep linking https://github.com/PrismLibrary
  9. 9. CONFIGURATION • Manually, by adding the following NuGet packages: • Prism.Core • Prism.Forms • Prism.xyz.Forms, where xyz is one of the supported dependency injection containers (Unity, Ninject, Autofact, etc.) • Automatically, with the project wizard:
  10. 10. DEPENDENCY INJECTION With the standard approach, objects that are used in a ViewModel are created at compile time: public MainViewModel MainViewModel { public MainViewModel() { DataService service = new DataService(); service.GetItems(); } }
  11. 11. THE PROBLEM DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems(); DataService service = new DataService(); service.GetItems();
  12. 12. DEPENDENCY INJECTION MainViewModel IDataService public MainViewModel(IDataService dataService) { } DataServiceTestDataService
  13. 13. DEPENDENCY INJECTION • In the App class you associate the interface with its concrete implementation: Container.RegisterType<IDataService, DataService>(); • In the constructor of the ViewModel, you create a dependency by adding a parameter to the class’ constructor: private readonly IDataService _apiService; public MainPageViewModel(IDataService apiService) { _apiService = apiService; } • You use the class in any method or property of your ViewModel
  14. 14. CONFIGURATION • Your App class needs to inherit from PrismApplication • RegisterTypes() method to register classes inside the dependency container. • OnInitialized() method to navigate to the main page of the app using the NavigationService provided by Prism KEYWORD: flexibility • Default naming convention: MainPage -> MainPageViewModel • You don’t like it? Feel free to override it and manually specify the connection in the dependency container. Container.RegisterTypeForNavigation<MainPage>(); Container.RegisterTypeForNavigation<DetailPage, MyCustomDetailViewModel>();
  15. 15. NAVIGATION • INavigationAware is an interface that you can implement in your ViewModels to get access to the following events: • OnNavigatedTo() when you navigate to the page • OnNavigatedFrom() when you navigate away from the page • OnNavigatingTo() when you are navigating to the page • NavigationService can be used to navigate from one page to another, with support to parameters: NavigationParameters param = new NavigationParameters(); param.Add("text", “This is a parameter"); await _navigationService.NavigateAsync("DetailPage", param); • In the OnNavigatedTo() method of the destination page you can retrieve the parameter
  16. 16. NAVIGATION • Deep link: you can create complex navigation paths and retain the stack of the pages await NavigationService.NavigateAsync("MainTabbedPage/NavigationPage /ShowsListPage/DetailPage?id=279121"); MainTabbedPage Navigation ShowsList Detail
  17. 17. HANDLING PLATFORM SPECIFIC CODE • Xamarin Forms allows to share business logic and user interface but, at some point, you need to write platform specific code • Xamarin Forms offers a DependencyService class and a Dependency attribute to handle this scenario Portable Class Library IShareService IosShareService DroidShareService UwpShareService [assembly: Dependency(typeof(UwpShareService))]
  18. 18. HANDLING PLATFORM SPECIFIC CODE WITH DI IShareService shareService = DependencyService.Get<IShareService>(); Container.RegisterInstance<IShareService>(shareService); • With a traditional dependency injection approach, you have first to get a reference to the platform specific service and then register it into the DI container • Prism automatically register every class tagged with the Dependency attribute inside the container, so you can just use it in your ViewModels private readonly IShareService _shareService; public MainPageViewModel(IShareService shareService) { _shareService = shareService; }
  19. 19. REFERENCES • Samples: https://github.com/qmatteoq/XamarinForms-Prism • Prism: https://github.com/PrismLibrary/ • Templates for Prism: https://marketplace.visualstudio.com/items?itemName=BrianL agunas.PrismTemplatePack • Blog posts with more detailed info about Prism: http://blog.qmatteoq.com/tag/prism/ • Blog posts to learn more about MVVM: http://blog.qmatteoq.com/the-mvvm-pattern-introduction/

×