Prism in Xamarin Forms Step by Step (Part. 1)

In this article, I will explain to you in a very simple way what Prism is, how to use it, and what you can do with it.

This article will include:

  • An overview of what Prism is
  • How to set up
  • How to connect Views with ViewModels
  • How to navigate and different types of navigation
  • Displaying alerts
  • Register dependencies

Let’s start with some theory…

In Xamarin Forms there are a lot of MVVM frameworks that you can use to develop better code based on MVVM pattern, to mention just a few: Prism, MvvmLight, FreshMvvm, MvvmCross, Exrin, etc.

Prism is a framework which embraces best coding practices to develop loosely coupled, maintainable, and testable applications. In simple words code better :).

With that definition maybe you are asking yourself why should I use Prism and not any of the other frameworks I mentioned above.

These are some of the reasons:

  • Prism is very complete, simple and handy. It handles navigation, events, modules, everything a small project to a large project might need
  • Due to loose coupling, it makes applications easier to test
  • Because Miguel de Icaza (Xamarin Co-Founder and CTO) says so 😛

Let’s set up

Ok, now that you know what Prism is, let’s set up your project.

The first you need to know is that there are 4 options of packages you can use.

Basically, the difference between them is the dependency container they use, you should choose it according to the type of the project you will develop. For example, if you are developing a small project might be a good option could be Autofac, or if you are looking for a better performance there are containers that do better in that sense than others.

In the following references, you will find a good way to learn more about each one and choose which one suits better for your project:

Ok, now we can set up  

Will be using Unity because is the most popular and personally I like it.

1-Install the Prism Package 

Go to your packages folder, click on “Add Packages”, choose Prism.Unity.Forms and install it in all your projects

2-Add the Prism reference in your App.xaml.cs file

Add the Prism reference xmlns:prism=clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms, and replace “Application” Root for “PrismApplication”

3- On your App class inherit from PrismApplication, add the Prism initializer parameter in the constructor and override the OnInitialized and RegisterTypes methods on App.xaml.cs 

Update: using Prism Version 7.0 > 

4-Add Platform initializers on iOS AppDelegate.cs and Android MainActivity.cs

Create a new class that implements IPlatformInitializer and pass it to the LoadApplication method.

Update: using Prism Version 7.0 > 

Let’s code

Now that we have the project set up, let’s start by creating a Page and a ViewModel, in my case will name it HomePage and HomePageViewModel. In Xamarin Forms normally for connecting them together, we use this.BindingContext = new HomePageViewModel();  on the HomePage constructor, but let’s see how Prism does this.

– Connecting Views with ViewModels

In Prism, there are two ways to connect a View with a ViewModel, both of them include going to your App.cs file and in the method call RegisterTypes, register all the pages which you will navigate.

1-Registering the view with the ViewModel associated 

Update: Using Prism Version 7.0 > 

In the first parameter you will specify the Page and in the second parameter the ViewModel associated to it.

2-Register the view and associate the ViewModel by naming convention 

In this case, you will only register the view and by using a naming convention, you will name your ViewModel with the same name of your Page, then you will add  “ViewModel” in the end. That automatically will resolve and associate this ViewModel with that Page.

Is important to know that the first option is faster than the second one. Since the second one uses reflection to get the ViewModel that needs to be associated with the Page.

– Let’s navigate

In Prism there are two types of navigations you can use:

1-Relative

It navigates to the Page you want in a relative way considering the current navigation stack history, would be the same as doing Navigation.PushAsync(); but smarter since if there’s not a NavigationPage on the stack it will navigate modal by default. Also, you have to specify the name of the page you want to navigate, in this example, I want to navigate to “HomePage”.

Also, if you want to simplify it a little bit more you can use the code:

By default, it will be relative.

2-Absolute

It navigates to the Page you want in an absolute way, that means when you do this navigation it will clear the navigation stack. So no matter what pages you had before, this page will be the “MainPage”, is the same of doing MainPage = new HomePage();.

Also as you can see here, it receives a Uri, basically your Uri can be anything with an absolute uri format, the important thing to considerate is that you have to put any uri + /PageYouWantToNavigate. In my case, I prefer to use the name of the project as my uri name.

– Use the Navigation Service in your ViewModel 

As you can see in the example above we used NavigationService, that is because that code was done in the App.cs and we have access to the NavigationService there, but if we want to use it in our ViewModel we won’t have the NavigationService available, so that’s when dependency injections comes to the rescue, if you want to use it you just have to inject it.

Really simple to do, you just have to inject your Navigation Service in your ViewModel constructor and done. Now you can use it in your ViewModels.

Note: In case you don’t know what dependency injection is and you want to learn more about it. This is a really good reference: http://www.theserverside.com/news/1321158/A-beginners-guide-to-Dependency-Injection

– Passing parameters

To pass parameters in Prism there are two ways to do it:

1-Using NavigationParameters

2-Using query string

As you can see here, in the first option I’m sending a NavigationParameters, which is a dictionary of objects and in the second option, I’m sending the parameters by including them in the URL using a query string.

– Receiving parameters

To receive navigation parameters, you just must implement the INavigationAware interface in the Page or ViewModel where you want to receive them.

As you can see here, it implemented two methods, OnNavigatedFrom and OnNavigatedTo, “OnNavigatedTo”  raises when you come from the other page to this page and the “OnNavigateFrom” raise when you navigated from this page to the other page.

In this case, we will receive the parameters on the method “OnNavigatedTo”  because we are navigating from HomePage to this page.

Prism > v7.2

– Go back 

Prism also has an option to go back to the previous page, you just have to use this code.

Also in the GoBackAsync method, you can pass parameters if you want.

– Display an alert

If you want to display an alert in Prism, there’s already an interface called IPageDialogService.

To use it, just we do the same we did with the NavigationService, inject it.

– Registering Services 

As a mentioned before, when using Prism you have to register all the pages which you will navigate, same happens with the services, all the services you will use have to be registered in order to be able to inject them.

For example:

Update: Using Prism Version 7.0 > 

Get and use the service:

At this point maybe you are wondering why I didn’t register NavigationService and PageDialogService. Well in Prism there are 3 services that are registered by default so you don’t have to register them: NavigationService, PageDialogService, EventAggregator.

That’s all, for now, you can see the full source code used in this example here:

https://github.com/CrossGeeks/Xamarin.Samples/tree/master/Xamarin%20Forms/PrismUnitySample

Sample Updated with Prism v7 > :

https://github.com/CrossGeeks/PrismV7Sample

Here are other good references about Prism:

Happy coding and see you in the next Prism article.

You may also like

9 Comments