Search code examples
prismmef

Where do I add a behavior to a single Region?


My problem is very simple, but all the options confuse me...

In my MEF/Prism-application, I want to attach a specific behavior to one specific region. The doumentation says, that you can do it that way:

IRegion region = regionManager.Region["Region1"];
region.Behaviors.Add("MyBehavior", new MyRegion());

But where should I put this? Is there some place, this is supposed to be done in a bootstrapper method? Currently, I am adding the behavior like this in the Loaded-event of the shell:

    /// <summary>
    /// Interaction logic for Shell.xaml
    /// </summary>
    [Export(typeof(Shell))]
    public partial class Shell
    {
        [ImportingConstructor]
        public Shell(IRegionManager regionManager, ElementViewInjectionBehavior elementViewInjectionBehavior)
        {
            InitializeComponent();
            Loaded += (sender, args) =>
                          {
                              IRegion region = regionManager.Regions[RegionNames.ElementViewRegion];
                              region.Behaviors.Add("ElementViewInjection", elementViewInjectionBehavior);
                          };
        }
    }

Is this a good solution. I'd rather do it in the bootstrapper, so that it is done in the same place as the other region behavior registrations (ConfigureDefaultRegionBehaviors()).

So, the question: Where is the best place to add the behavior to one single region?


Solution

  • We had the same issue - in the end we just checked the region name in the region behaviour and acted only if it was that region that we wanted, kind of sucks because you are attaching the behaviour to all regions - but for us it was better than the suggested solution..

    An example looks like :

    public class TrackViewOpenerBehaviour : IRegionBehavior
    {
        public IRegion Region { get; set; }
        public void Attach()
        {
            if (this.Region.Name == ApplicationRegions.WorkspaceRegion
                || this.Region.Name == ApplicationRegions.DialogRegion)
            {
                 this.Region.Views.CollectionChanged += (sender, e) =>
                 {
                     //Code Here.
                 };
    
            }
        }
     }
    

    I always thought maybe we could create a behaviour that was responsible for attaching other behaviours to specfiic regions for us, then we could register that in the bootstrapper - but never got round to it.