如何在Prism中动态加载特定区域中的视图

时间:2012-09-26 09:09:13

标签: prism silverlight-5.0

在Prism Silverlight5中,我有一个shell分为两个垂直区域(leftRegion,rightRegion)&在Module1中有2个视图,即(View1,View2)。
在leftRegion中我加载了一个View1,它有一个按钮。
我想使用ViewModel& amp;动态加载View2在rightRegion上。 MEF.ViewModel代码是:

    [Export(typeof(LeftViewViewModel))]
public class LeftViewViewModel:ViewModelBase,IViewModel
{
    [Import]
    public IRegionManager CullingRegion { get; set; }

    [ImportingConstructor]
    public LeftViewViewModel(LeftView view)
        :base(view)
    {
        LoadCommand = new DelegateCommand(LoadControl,CanLoadControl);
    }

    private void LoadControl()
    {
        CullingRegion.RegisterViewWithRegion("RightRegion", typeof(RightView));
    }

    protected bool CanLoadControl()
    {
        return true;
    }

    public DelegateCommand LoadCommand { get; set; }
}

LeftView.xaml.cs是:

    [Import]
    public ViewModels.IViewModel ViewModel
    {
        get { return (IViewModel) DataContext; }
        set { DataContext = value; }
    }

IModule实现是:

[ModuleExport(typeof(CullingModuleModule1))]
public class CullingModuleModule1:IModule
{
    [Import]
    public IRegionManager CullingRegion { get; set; }

    public void Initialize()
    {

        CullingRegion.RegisterViewWithRegion("ShellContentRegion", typeof (Container));
        CullingRegion.RegisterViewWithRegion("LeftRegion", typeof(LeftView));


    }
}

1 个答案:

答案 0 :(得分:0)

首先,我认为您的ViewModel不应该被View引用 您可能需要使用MEF查看View Injection。 正如我在多个帖子中看到的那样:

        [Export]
        public class YourViewClassName : UserControl
        {
            public YourViewClassName()
            {
            }
            [Import]
            public ILeftViewModel 
            {
                get { return (ILeftViewModel )DataContext; }
                set { DataContext = value; }
            }
        }

        [Export(typeof(LeftViewViewModel))]
        public class LeftViewViewModel : ILeftViewModel //ILeftViewModel inherits from IViewModel
        {
            public LeftViewViewModel()
            {
            }
        }

内部模块初始化程序:

CullingRegion.Regions[YourRegionName].Add(ServiceLocator.Current.GetInstance<YourViewClassName>());

希望有所帮助