Prism in Xamarin Forms

In this article I am going to explain how to use and implement Prism in Xamarin forms application. I will explain you how to use MVVM desing pattern using of Prism MVVM.

1. Create new Xamarin forms solution.
2. Add Prism.Unity.Form NuGet package

Prism.Unity.Forms add in all projects (portable, android and ios)

3. Add Prism namespace reference inside App.xaml page.

xmlns:prism=clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms and replace “Application” class to prism:PrismApplication

Before Adding Prism

 

After adding Prism Reference 

 

4. Replace inherited class from Application to PrismApplication and change constructor with IPlatformInitializer parameterized and override the OnInitialized and RegisterTypes functions into your app.xaml.cs class file.

 

Before Adding Prism in app.xaml.cs

 

After Adding Prism in ap.xaml.cs

Hurray, We are done to adding Prism in our application. Next step how to use structure.
5. Create Folders in your Portable Library.
  1. Views
  2. Models
  3. ViewModels

Add View in your View Folder. Like: HomePage.xaml 

Add ViewModel in your ViewModels Folder: HomPageViewModel.cs

Note: Your ViewModel must be same name as your View name and at end just add ViewModel Keyword.
For Example:
Views>HomePage.xaml
ViewModels>HomePageViewModel.cs

 

6. Set Start up navigation page in App.xaml.cs

Register your view for Navigation in  RegisterTypes method.

NavigationPage is RootPage of the application.

  protected override void RegisterTypes(IContainerRegistry containerRegistry)
  {
     containerRegistry.RegisterForNavigation<NavigationPage>();
     containerRegistry.RegisterForNavigation<HomePage>();
  }

Set your first first for navigation inside OnInitialized() method.

  protected override void OnInitialized()
  {
      InitializeComponent();

      NavigationService.NavigateAsync(NavigationPage/HomePage);
  }

App.xaml.cs Code:

Cheers and enjoy coders. Thanks 🙂

One reply to Prism in Xamarin Forms

  1. Nice article. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *