Tuesday, February 24, 2009

Lack of AttachNewRegion method in Prism 2.0

Today I have switched to Composite WPF and Silverlight 2.0 (known as Prism 2.0) in one of my current projects. The transition was quite smooth (I used a guide which I found here), although I found one issue - the IRegionManager interface does not contain the AttachNewRegion method :( This made me very unhappy because I used this method in the implementation of a IMenuService which is responsible for managing the main menu control within my application by exposing a friendly interface to all modules. After small source code investigation I realized that indeed there's no sign of the mentioned method. After reading interesting post here, I decided to write one myself, which was a trivial task ;) Here's the code:



using System;
using System.Windows;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;

namespace Mammoth.Presentation.Infrastructure.Common
{
public static class RegionManagerExtensions
{
public static void AttachNewRegion(this IRegionManager regionManager, object regionTarget, string regionName)
{
if (regionManager.Regions.ContainsRegionWithName(regionName))
throw new ArgumentException("Region already exists.", regionName);

RegionManager.SetRegionManager((DependencyObject) regionTarget, regionManager);
RegionManager.SetRegionName((DependencyObject) regionTarget, regionName);
}
}
}


As you can see, this is a very simple extension method that extends the IRegionManger interface. Inside, I simply set the region manager and the region name on the desired UI element.

This solution is very simple, still it works fine (at least for me). If you have any troubles with it, let me know.

No comments: