WPF Prism concepts: regions

If you are a developer in the Microsoft environment and if you’re developing desktop apps, it’s likely that you’ve read something about Prism.  If you don’t then this is what Prism is about:

Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms. (from the Prism’s Official GitHub description)

The Prism documentation is very detailed but with this blog post we are more practical and examples-driven. If you want to dive into the details of Prism the official documentation is the best place.

Definition

A region is a placeholder in the shell of a Prism application for content that will be loaded at runtime. Regions are defined as UI elements like ContentControl, ItemsControl, TabControl or a custom control.

The content of a region is a view. We can access regions in a decoupled way by their name and they support dynamically adding or removing views.

Example with view discovery

So now it’s coding time!

The first thing we need is to setup our app to be a Prism-app. At this point we have a clean Prism-App.

Then, we create a region in our MainWindow. This is the XAML code.

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <Grid>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
    </Grid>
</Window>

We can see that the regions are defined as XAML attached properties. In the code above our region is called RegionA.

Now we have our region defined but no content to load into. We create a new user control in the Views subfolder and name it ViewA.xaml.

Immagine

In this class in the XAML part we write:

<UserControl x:Class="XXXXX.Views.ViewA"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"              >
    <Grid>
        <TextBlock Text="View A" FontSize="38" />
    </Grid>
</UserControl>

That’s good! We have our region and a view. Now it’s time to tell Prism that RegionA is the target where to load the ViewA view. In the code-behind of the MainWindows.xaml we write:

using Prism.Regions;
using System;
using System.Windows;

namespace XXXXX.Views
{

    public partial class MainWindow : Window
    {
        public MainWindow(IRegionManager regionManager)
        {
            InitializeComponent();

            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }
            regionManager.RegisterViewWithRegion("RegionA", typeof(ViewA));
        }
    }
}

With the above code for the constructor we are registering that RegionA has to be populated with an instance of ViewA view. The region manager is passed as a parameter by the DI container (in our case Unity). This technique is called View Discovery. The result is:

Screenshot_1

Example with View Injection

Now we explore the View Injection technique that enables us to load and unload the content of a region dynamically at runtime.

We create a new view, ViewB, like we did for ViewA under the Views folder.

<UserControl x:Class="XXXXX.Views.ViewB"              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"            >
    <Grid>
        <TextBlock Text="View B" FontSize="38" Foreground="#FF0023FF" />
    </Grid>
</UserControl>

We edit the MainWindow to add another region and a button to fire our code:

<Window x:Class="XXXXX.Views.MainWindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:prism="http://prismlibrary.com/"                Title="MainWindow" Height="300" Width="300">
    <StackPanel>
        <ContentControl prism:RegionManager.RegionName="RegionA" />
  <Button Click="Button_Click" >Load region B</Button>
<Button Click="Button_Clear_Click" >Clear region B</Button>
<ContentControl prism:RegionManager.RegionName="RegionB" />
    </StackPanel>
</Window>

And the code behind

public partial class MainWindow : Window
    {

        private readonly IRegionManager _regionManager;
        private readonly IUnityContainer _container;

        public MainWindow(IRegionManager regionManager, IUnityContainer container)
        {
            InitializeComponent();
            //view discovery
            if (regionManager == null)
            {
                throw new ArgumentNullException(nameof(regionManager));
            }

            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            _regionManager = regionManager;
            _container = container;

            _regionManager.RegisterViewWithRegion(RegionNames.RegionA, typeof(ViewA));

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //We get from the container an instance of ViewB.
            var view = _container.Resolve<ViewB>();

            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //We inject the view into the region.
            region.Add(view);
        }

  private void Button_Clear_Click(object sender, RoutedEventArgs e)
        {
            //We get from the region manager our target region.
            IRegion region = _regionManager.Regions["RegionB"];

            //Clears the content.
            region.RemoveAll();
        }

    }

What we’re doing here is to get our target region by using the RegionManager class.

The RegionManager class is responsible for creating and maintaining a collection of regions for the host controls. The RegionManager uses a control-specific adapter that associates a new region with the host control. The following illustration shows the relationship between the region, control, and adapter set up by the RegionManager. (Prism official docs)

When we have a reference of the region (RegionB in this case) we can add or remove content with the Add or the Remove/RemoveAll methods.

Screenshot_2

TL;DR

In this blog post we explored the concept of Region. Regions are useful conteiners to create our UI in a structured and dynamic way. We loaded content with the discovery and the injection technique.

In the next blog post we’ll study other Prism’s concepts.

Happy coding!

Reference

Prism official documentation (http://prismlibrary.readthedocs.io/en/latest/)
Prism Github page (https://github.com/PrismLibrary)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.