Updated for Prism.Forms 5.7.0-pre-1 (6/8/2015)
Just fives days ago, Microsoft announced that the ever popular and highly adopted Patterns & Practices Prism Library was being open sourced and is going to be run by a new team. In that time, we have been hard at work getting a version of Prism out that supports the new Xamarin.Forms platform. I am excited to announce, that we have released a very early preview of Prism for Xamarin.Forms that is available on NuGet now.
This preview has the following features included:
- IoC with Unity (you will be able to provide your own container in a future release)
- Event aggregation
- MVVM support
Let’s see what it takes to create a Xamarin.Forms application with Prism. Let’s start by creating a new blank Xamarin.Forms Portable application.
Next, lets go ahead and add our references to Prism for Xamarin.Forms using NuGet. Right-click the Solution and click on “Manage NuGet Packages”. Since this is a preview, you will have to change the package inclusion from “Stable Only” to “Include Prerelease”. Now simply search for the package “Prism.Forms”.
Make sure you add the package to all the projects in the solution.
Next, we need to create a Bootstrapper class. If you are a current Prism user, you are very familiar with this bootstrapper. If not, the bootstrapper is simply a class that initializes all the services that Prism will be using. This is what a simple bootstrapper class looks like.
As you you can see we have two methods that we must implement. CreateMainPage will return the page we want to use as the root page of the application. RegisterTypes will be used to register our application types with our container of choice. In the Preview, we are using Unity.
Now, let’s wire up our bootstrapper with our application. Open up the App.cs and remove all the code in the class constructor. Now we simply create an instance of our bootstrapper and call Run(this).
Since we need a main page let’s go create one. Let’s start by adding two folders to our application. We want a folder for our Views, and a folder for our ViewModels. I mean, we will be using MVVM after all. Your project should look like this:
In the Views folder create a MainPage, and return that page in your Bootstrapper.CreateMainPage method. While you are in there, go ahead and remove the NotImplementedException line in the RegisterTypes. We’ll see that in action later.
Now, let’s put some XAML in our MainPage view. This is what I’ll be using for this demo.
As you can see, we are expecting a ViewModel to bind to our MainPage view, so let’s go ahead and create one of those. Right-click the ViewModels folder and add a new class. Name it MainPageViewModel. It is important that you name the ViewModel <PageName>ViewModel. We will see why later. This is what my ViewModel looks like:
BindableBase is a class provided by Prism that has your basic INotifyPropertyChanged implementation in it, and a helper method used for setting property values. You may also recognize Prism’s DelegateCommand too.
Now, we have one more step. We need to create the binding between the View and the ViewModel. We will be using Prism’s ViewModelLocator to accomplish this. So open up our MainPage.xaml and add a namespace to Prism’s ViewModelLocator. Once you have added the namespace, set the AutoWireViewModel attached property to True. That’s it! This is what our View looks like now.
Run the application, and let’s see what we have.
As you can see, our MainPage is loaded, and the MainPageviewModel has been intantiated and set as the binding context of the page. very cool. So how did this work? Well, the Prism ViewModelLocator is convention based. To learn more about the ViewModelLocator, read the Getting Started with Prism’s ViewModelLocator post.
Now, let’s create a second View, and ViewModel that looks just like our MainPage, and start adding navigation to it. This is what your solution should look like now.
Now in order to obtain the navigation service, we simply need to request it in the ViewModel constructor by adding a parameter of type INavigationService. It’s important that we name the parameter “navigationService”. This is case sensitive and will not work properly if not named correctly. This will give use access to the proper INavigationService we need in order to navigate within our Xamarin.Forms application. Now that we have the INavigationService, we can navigate to our ViewA created earlier. Here is our MainPageViewModel now:
As you can see we are calling NavigationService.Navigate(“ViewA”), but how does that work? Well, we need to actually register that view for navigation in our bootstrapper. So let’s go back to the bootstrapper, and register the view with our container.
By default, Prism will use the name of the object being registered as convention, but you can override that by providing your own key as a parameter. There is also an overload that allows you to use a class type instead of a string. Now when we run the application and click the button, we will navigate to our ViewA as expected.
Now, let’s say we wanted to pass parameters to ViewA when we navigate to it. Well, that’s easy. We simply create a new NavigationParameters object and send them along with the navigation call. This is what our MainPage.Navigate method looks like now.
Now, keep in mind that you can pass anything as a parameter. You are not limited to just string, and you are not limited to one parameter. You can pass any number of parameters. The first parameter in the Add method is the unique key for the value. This will be used to get the value from the parameters in the target view. The second parameter is obviously the value.
So how do we get these parameters from the target view we are navigating to? Well that’s easy. We just need to implement the INavigationAware interface.
This interface allows us to participate in the navigation process and gain access to the parameters being passed between ViewModels. There is also the IConfirmNavigation interface which allows you to prevent a navigation from occurring based on the business logic from within the ViewModel. Now when we run the application, we can pass a parameter to the target ViewA and display it in the view.
The last think I was to show you in this post is the IEventAggregator. The IEventAggregator gives you access to a publish/subscribe type eventing system throughout your application. It is similar to the MessagingCenter built into Xamarin.Forms, but better. To use it, you first nee to create a PubSubEvent. Creating an event is easy. Just create a class the derives form PubSubEvent<T>, where <T> is the object type of the payload, or message, that you will be sending with the event.
Now you need a publisher to publish/send the event. To publish the event, simply get the IEventAggregator in the constructor of your ViewModel and call the Publish method as follows.
Now, you need a subscriber. In this case it will be our MainPageViewModel. Modify the MainPageViewModel as follows:
As you can see, when the even is published by ViewAViewModel, the MainPageViewModel will respond to the event, take the payload and set it’s Title property to the value of the GoBackEvent payload.
Thanks for hanging in there with me in this somewhat long post. I hope this gives you enough information and guidance to get started using Prism for Xamarin.Forms. I wanted to get this preview out to the community as quickly as possible in order to get your feedback on the direction Prism for Xamarin.Forms is going. Let me know what you think about the API. Tell me what sucks, but better yet, tell me what is great. Be sure to check out this code on my GitHub, and start playing around. If you have an idea that you would like to see implemented, be sure to fork our repository and submit a pull request.