Custom region adapter (PRISM)

2k views Asked by At

I have implemented a custom region adapter for a ToolBar as explained in this link http://compositewpf.codeplex.com/discussions/250892. I get this error:'ToolBarRegionAdapter' does not contain a constructor that takes 0 arguments. Here my code:

public class ToolBarRegionAdapter : RegionAdapterBase<ToolBar>
{
    public ToolBarRegionAdapter(IRegionBehaviorFactory behaviorFactory)
        : base(behaviorFactory)
    {
    }

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

    protected override void Adapt(IRegion region, ToolBar regionTarget)
    {
        region.Views.CollectionChanged += (sender, e) =>
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (FrameworkElement element in e.NewItems)
                    {
                        regionTarget.Items.Add(element);
                    }
                    break;

                case NotifyCollectionChangedAction.Remove:
                    foreach (UIElement elementLoopVariable in e.OldItems)
                    {
                        var element = elementLoopVariable;
                        if (regionTarget.Items.Contains(element))
                        {
                            regionTarget.Items.Remove(element);
                        }
                    }
                    break;
            }
        };
    }
}

I have overrided the ConfigureRegionAdapterMappings() method in my Bootstrapper (my Bootstrapper inherits from MefBootstrapper). Here the code:

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
    RegionAdapterMappings regionAdapterMappings = base.ConfigureRegionAdapterMappings();
    regionAdapterMappings.RegisterMapping(typeof(ToolBar), new ToolBarRegionAdapter());
    return regionAdapterMappings;
}

When I compile I get this error:'ToolBarRegionAdapter' does not contain a constructor that takes 0 arguments. Which is actually true, the contructor takes a IRegionBehaviorFactory but I don't have that object in my code. But in the examples I've seen, the region adapter is instantiated without any argument. Any idea why? Thanks!

2

There are 2 answers

3
Haukinger On BEST ANSWER

While constructor injection is always preferred, when it's not possible, as in your case, go for the service locator...

ServiceLocator.Current.GetInstance<IRegionBehaviorFactory >()

... as is shown in the link you provided, btw...

1
galakt On

You are wrong with how you add adapter:

Must be

protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
    RegionAdapterMappings regionAdapterMappings = base.ConfigureRegionAdapterMappings();
    regionAdapterMappings.RegisterMapping(typeof(ToolBar), Container.Resolve<ToolBarRegionAdapter>());
    return regionAdapterMappings;
}