MEF、Prism 和导航上的新视图实例

MEF, Prism and new view instance on navigation

下面的代码适用于视图的共享实例。现在我想要实现的是每次我导航到 ViewB 我想要一个新的视图实例及其支持视图模型。我已经尝试了以下的各种组合,但它们似乎最终都以 RequestNavigate 我第二次尝试导航到 ViewB 时无声无息地失败...

我还尝试在视图导航到一次后将 IsNaviagtionTarget 设置为 false。

引导程序:

public void Initialize()
{
    _regionManager.RegisterViewWithRegion(RegionNameConstants.MainRegion, typeof(ViewA));
    _regionManager.RegisterViewWithRegion(RegionNameConstants.MainRegion, typeof(ViewB));
}

ViewB (class):

[RegionMemberLifetime(KeepAlive = false)]
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
internal partial class ViewB
{
    [ImportingConstructor]
    public ViewB(ViewBViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
    }
}

ViewBViewModel:

[Export(typeof(ViewBViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
internal class ViewBViewModel : BindableBase, INavigationAware
{
    public void OnNavigatedTo(NavigationContext navigationContext)
    {
    }

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
    }
}

ViewA 只是有一个带有调用命令的按钮:

ViewA 导航命令:

public override void Execute(object parameter)
{
    _regionManager.RequestNavigate(RegionNameConstants.MainRegion, new Uri(nameof(ViewB), UriKind.Relative));
}

不要在引导程序中向区域管理器注册typeof(ViewB)

public void Initialize()
{
    _regionManager.RegisterViewWithRegion(RegionNameConstants.MainRegion, typeof(ViewA));
}

并且由于您正在导航到 nameof(ViewB) 的 Uri,因此您还应该导出合同名称为 nameof(ViewB) 的视图:

[Export(nameof(ViewB))]
[PartCreationPolicy(CreationPolicy.NonShared)]
[RegionMemberLifetime(KeepAlive = false)]
internal partial class ViewB
{
    [ImportingConstructor]
    public ViewB(ViewBViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
    }
}

那么每次使用以下方法导航到 ViewB 时,您都应该获得一个新的 ViewB 实例:

_regionManager.RequestNavigate(RegionNameConstants.MainRegion, new Uri(nameof(ViewB), UriKind.Relative));