Prism Regions in Xamarin Forms

If you don’t know what Prism is, I recommend that you read this article first.

On Prism 8.0, the Prism Team released an amazing feature called Regions, which gives us a lot of flexibility in handling different views on a page. To understand it, let’s see the following use case:

We have a TabbedView (Or two buttons), depending on the selected section option, we want to show one view or the other. What we usually do is creating different content views for each section and handle all the ViewModel logic for each view in the Page’s ViewModel.

The problem with this approach is that it doesn’t give us a lot of flexibility and code segmentation since we have all the logic for both sections in the same ViewModel.

For this and other similar use cases, we have Regions.

“A Region is a Composite Control. If you’re coming from the context of traditional Prism.Forms Page based app design just think whatever you had on the Page but a small section that may need to change or be reused across various Pages.”. by Dan Siegel

Let’s start

1.Install the Prism.Forms.Regions package

2.Define your regions

For this example, I’ll create two regions, one for a HomeView and another one for a ContactsView.

HomeView.xaml

HomeViewModel.cs

ContactsView.xaml

ContactsViewModel.cs

3.Create the Page where you want to use your Regions

MainPage.xaml

You need to set the name of the Region by using prism:RegionManager.RegionName=”HomeRegion”

4.Connect Regions

On the ViewModel, let’s inject the IRegionManager and in the Initialize method call RequestNavigate method for each region, this will connect the Region with the View by using the Region Name we previously set in the View and the name of the View.

ex. _regionManager.RequestNavigate(“<RegionNameUsedInThePageUI>”, “<ViewName>“, RegionNavigationCallback);

5.Register your Page and Regions

Limitations

  • At the time I wrote this article, Region only supports ContentView, CarrouselView, Frame, ScrollView, FlexLayout, CollectionView (Experimental).
  • There is a known issue (Prism.Regions.IActiveRegionHelper crash) when using Region with a Prism Container other than Prism.DryIoc. Check here for more information.

That’s all for now, check the full code here.

Happy coding!

You may also like

1 Comment

  1. Great article!

    Maybe this could come in handy in a white-label (private label?) app where, for example, certain customers have their own unique startpage. Would love to hear your thoughts on this. 🙂