自定义区域适配器(PRISM)

时间:2016-11-13 20:22:14

标签: c# wpf mvvm prism regionadapter

我已经为ToolBar实现了自定义区域适配器,如此链接thaw中所述。我收到此错误:'ToolBarRegionAdapter'不包含带0参数的构造函数。 这是我的代码:

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;
            }
        };
    }
}

我已经覆盖了Bootstrapper中的ConfigureRegionAdapterMappings()方法(我的Bootstrapper继承自MefBootstrapper)。代码如下:

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

当我编译时,我收到此错误:'ToolBarRegionAdapter'不包含带0参数的构造函数。实际上,构造函数采用IRegionBehaviorFactory但我的代码中没有该对象。但是在我看过的例子中,区域适配器是在没有任何参数的情况下实例化的。 知道为什么吗?谢谢!

2 个答案:

答案 0 :(得分:1)

虽然构造函数注入总是首选,但如果不可能,就像在你的情况下一样,去服务定位器......

ServiceLocator.Current.GetInstance<IRegionBehaviorFactory >()

...如您提供的链接所示,顺便说一句......

答案 1 :(得分:1)

您添加适配器的方式有误:

必须

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