prism - 我在哪里向单个区域添加行为?

标签 prism mef

我的问题很简单,但所有的选项都让我感到困惑......

在我的 MEF/Prism 应用程序中,我想将特定行为附加到一个特定区域。 doumentation 说,你可以这样做:

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

但是我应该把它放在哪里?有没有地方,这应该用 bootstrap 方法完成?目前,我在 shell 的 Loaded-event 中添加了这样的行为:
    /// <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);
                          };
        }
    }

这是一个很好的解决方案。我宁愿在 bootstrap 中执行此操作,以便在与其他区域行为注册 ( ConfigureDefaultRegionBehaviors() ) 相同的位置执行此操作。

那么,问题是:将行为添加到单个区域的最佳位置在哪里?

最佳答案

我刚刚提出了一个稍微改进的解决方案,在行为中使用静态字符串集合来添加区域以将行为附加到。

public class ViewModelInjectionBehavior : RegionBehavior, IDisposable
{
    private static List<string> _regionNames; 

    public static List<string> Regions
    {
        get { return _regionNames ?? (_regionNames = new List<string>()); }
    }       

    protected override void OnAttach()
    {
        if (Regions.Contains(Region.Name)) {...}          
    }        
}

然后在我的 bootstrap 中,我可以定义区域:
    protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
    {
        var behaviorFactory = base.ConfigureDefaultRegionBehaviors(); 

        ViewModelInjectionBehavior.Regions.Add(RegionNames.ElementViewRegion);
        behaviorFactory.AddIfMissing("ElementViewInjectionBehavior", typeof(ViewModelInjectionBehavior));

        return behaviorFactory;
    }

至少,该行为现在普遍可用......

关于prism - 我在哪里向单个区域添加行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13706489/

相关文章:

c# - 如何在 Prism 应用程序中手动解析类型时获得正确的 INavigationService 实例

wpf - 导入具有特定参数的类

c# - MEF 中的 Dll 版本控制

c# - MEF 阻止类被手动实例化

c# - 在编辑项目的属性后对 ObservableCollection 进行排序

WPF Prism CompositeCommand 禁用按钮

c# - 如何使用 MEF 的 GetExport\ImportDefinition?

c# - MEF - 从其他 View 显示 View

wpf - Prism/WPF 中的新外壳/窗口显示错误 View

wpf - 为什么在 MVVM 应用程序的 Controller 构造函数参数中使用 Func<>