Create a Custom Prism RegionAdapter

April 18th, 2012

Don’t want to read the article?  Watch the video tutorial on Xaml TV.

Prism provides 4 region adapters out of the box for you:

  • ContentControlRegionAdapter
  • SelectorRegionAdaptor
  • ItemsControlRegionAdapter
  • TabControlRegionAdapter (Silverlight only)

Well, what happens when you want to use a different control as a region host?  Simple.  You need to write a custom region adapter for it.  Is it hard you ask?  No it is quite easy.  Let’s write one for the StackPanel.

Start by creating a class the derive from and implements the base abstract class RegionAdapterBase<T>.

public class StackPanelRegionAdapter : RegionAdapterBase<StackPanel>
{
    public StackPanelRegionAdapter(IRegionBehaviorFactory factory)
        : base(factory)
    {

    }

    protected override void Adapt(IRegion region, StackPanel regionTarget)
    {
        region.Views.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (FrameworkElement element in e.NewItems)
                    {
                        regionTarget.Children.Add(element);
                    }
                }

                //implement remove
            };
    }

    protected override IRegion CreateRegion()
    {
        return new AllActiveRegion();
    }
}

Notice that there are two methods we need to implement. Adapt and CreateRegion.  CreateRegion return the type of region we will need.  In our case we want to support multiple views so we need to return an instance of an AllActiveRegion.  If we only needed support for one view at a time we would return a SingleActiveRegion.  The Adapt method is responsible for adapting the region to our control.  This is where we will add and remove the views to or host control.

Now we simply have to tell Prism about our new RegionAdapter.  We do this in the bootstrapper.  Simply override the ConfigureRegionAdapterMappings method as follows:

protected override Microsoft.Practices.Prism.Regions.RegionAdapterMappings ConfigureRegionAdapterMappings()
{
    RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();
    mappings.RegisterMapping(typeof(StackPanel), Container.Resolve<StackPanelRegionAdapter>());
    return mappings;
}

That’s it.  Now you can use a StackPanel as a region host:

<StackPanel Orientation="Horizontal"
            prism:RegionManager.RegionName="MyRegion" />

 

Download the sample application.

  • David Wojo

    Good stuff, Brian.