Xamarin.Forms - Getting Started With Prism

Introduction

 
Xamarin.Forms - Getting Started With Prism 
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 

MVVM

 
MVVM - Model View ViewModel
 
Xamarin.Forms - Getting Started With Prism
 
MVVM Is the design pattern to separate the user interface & business logic concerns. I suppose that you heard something about it. This pattern created by Microsoft is widely used with applications created with .NET Framework but not only because you can also use it with Xamarin.
 

Prism

Xamarin.Forms - Getting Started With Prism 
Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms. Prism provides an implementation of a collection of design patterns that are helpful in writing well-structured and maintainable XAML applications, including MVVM, dependency injection, commands, EventAggregator, and others.
 
Prism Containers
  1. Unity
  2. DryIoc 
Unity is the container I use and recommend the most. Unity is the most popular container due to it being the container that Brian has used for years and it is the first (and for a long time only) container available in the Templates. Unity is also about average with regards to its benchmark performance.
 
DryIoc is the container  under active development, it's very fast, and works well with the current release of Prism. Also important is that when I have had questions or issues the maintainer has been very quick to address the issue or answer the question I had. It's for all of these reasons I continue to recommend the container.
 

Go with Prism Unity Container

 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 
Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.
 
Create a new or existing Xamarin forms (.Net standard) Project with Android and iOS Platform.
 
Xamarin.Forms - Getting Started With Prism
 

Install "Prism.Unity.Forms" Nuget

 
Now, add the following NuGet Packages.
  • Prism.Unity.Forms
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Prism.Unity.Forms" and add Package. Remember to install it for each project (.NET Standard, Android, iO, and UWP).
 
Xamarin.Forms - Getting Started With Prism 
 

Change Application to PrismApplication

 
After installing Prism.Unity.Prism, Change Application to PrismApplication in App.Xaml
 
App.xaml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms"   
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
  4.              xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms"  
  5.              x:Class="XMonkey.App">  
  6.     <Application.Resources>  
  7.           
  8.     </Application.Resources>  
  9. </prism:PrismApplication>  

Register NavigationService

 
Change application to PrismApplication and add IPlatformInitializer to App Constructor.
 
Then register your content page and ViewModel using IContainerRegistry
  • override OnInitialized (Initialize Components)
  • override RegisterTypes (Navigation Service Register)
Refer to the following code snippet,
  1. using Prism;  
  2. using Prism.Ioc;  
  3. using Prism.Unity;  
  4.   
  5.   
  6. public partial class App : PrismApplication  
  7.     {  
  8.   
  9.         //public App()  
  10.         //{  
  11.         //    InitializeComponent();  
  12.   
  13.         //    //DependencyService.Register<MockDataStore>();  
  14.         //    Routing.RegisterRoute("aboutPage", typeof(AboutPage));  
  15.         //    Routing.RegisterRoute("itemsPage", typeof(ItemsPage));  
  16.         //    MainPage = new AppShell();  
  17.         //}  
  18.  
  19.         #region Prism  
  20.   
  21.         public App(IPlatformInitializer platformInitializer = null) : base(platformInitializer) { }  
  22.   
  23.         protected override void OnInitialized()  
  24.         {  
  25.             InitializeComponent();  
  26.             NavigationService.NavigateAsync(PageConstants.MY_PAGE);  
  27.               
  28.   
  29.         }  
  30.         protected override void RegisterTypes(IContainerRegistry containerRegistry)  
  31.         {  
  32.             containerRegistry.RegisterForNavigation<AboutPage, AboutPageViewModel>();  
  33.             containerRegistry.RegisterForNavigation<MyPage, MyPageViewModel>();  
  34.         }  
  35.  
  36.          
  37.         #endregion  
  38.   
  39.     }  

Platform Setup

 
Android
 
Need to change IPlatformInitializer in LoadApplication.
 
MainActivity.cs
  1. using Prism;  
  2. using Prism.Ioc;  
  3.   
  4. namespace XMonkey.Droid  
  5. {  
  6.     [Activity(Label = "XMonkey", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]  
  7.     public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity  
  8.     {  
  9.         protected override void OnCreate(Bundle savedInstanceState)  
  10.         {  
  11.             TabLayoutResource = Resource.Layout.Tabbar;  
  12.             ToolbarResource = Resource.Layout.Toolbar;  
  13.   
  14.             base.OnCreate(savedInstanceState);  
  15.   
  16.             global::Xamarin.Forms.Forms.SetFlags("Shell_Experimental""Visual_Experimental""CollectionView_Experimental""FastRenderers_Experimental");  
  17.             Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
  18.             global::Xamarin.Forms.Forms.Init(this, savedInstanceState);  
  19.               
  20.         //Change LoadApplication IPlatformInitializer  
  21.             LoadApplication(new App(new AndroidInitializer()));  
  22.         }  
  23.   
  24.         public class AndroidInitializer : IPlatformInitializer  
  25.         {  
  26.             public void RegisterTypes(IContainerRegistry containerRegistry)  
  27.             {  
  28.             }  
  29.         }  
  30.   
  31.         public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
  32.         {  
  33.             Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  34.   
  35.             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  36.         }  
  37.     }  
  38. }  
iOS
 
Need to change IPlatformInitializer in LoadApplication.
 
AppDelegate.cs
  1. using Prism;  
  2. using Prism.Ioc;  
  3. using UIKit;  
  4.   
  5. namespace XMonkey.iOS  
  6. {  
  7.       
  8.     [Register("AppDelegate")]  
  9.     public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate  
  10.     {  
  11.           
  12.         public override bool FinishedLaunching(UIApplication app, NSDictionary options)  
  13.         {  
  14.             Xamarin.Calabash.Start();  
  15.               
  16.             global::Xamarin.Forms.Forms.Init();  
  17.   
  18.         //Change LoadApplication IPlatformInitializer  
  19.             LoadApplication(new App(new iOSInitializer()));  
  20.               
  21.             return base.FinishedLaunching(app, options);  
  22.         }  
  23.     }  
  24.   
  25.     public class iOSInitializer : IPlatformInitializer  
  26.     {  
  27.         public void RegisterTypes(IContainerRegistry containerRegistry)  
  28.         {  
  29.         }  
  30.     }  
  31. }  

MVVM BindingContext

 
You don't need to set BindingContext to your ViewModel to ContentPage. Just create a ContentPage name ending with Page. (Ex: MyPage). Create a ViewModel name staring with ContentPage Name (ex: MyPageViewModel).
 
Xamarin.Forms - Getting Started With Prism 
 
ViewModelLocator
 
If Viewmodel BindingContext is not working, follow the below steps.
 
ContentPage.cs 
  1. ViewModelLocator.SetAutowireViewModel(this,true);    
ContentPage.Xaml
  1. xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"  
  2. prism:ViewModelLocator.AutowireViewModel="True"  
Click the "Play" button to try it out.
 
Xamarin.Forms - Getting Started With Prism 
 
Wow, it's working.Xamarin.Forms - Getting Started With Prism
 
I hope you have understood how to how to use Prism in existing Xamarin.Forms app.
 
Thanks for reading. Please share your comments and feedback. Happy Coding Xamarin.Forms - Getting Started With Prism


Similar Articles