我有一个看起来像工具栏的外壳,并定义了我的主要区域(一个包装面板)。我需要做的是能够将小部件添加到shell中,并在单击小部件时打开一个新窗口(视图)。下面是我到目前为止有:在视图模型类中访问统一容器
我创建了一个模块类增加了一个以主要区域:
public class MyModule : IModule
{
protected IUnityContainer Container { get; private set; }
public MyModule(IUnityContainer container)
{
Container = container.CreateChildContainer();
}
public void Initialize()
{
var regionManager = Container.Resolve<IRegionManager>();
MyModuleView myModuleView = new MyModuleView();
regionManager.Regions["MainRegion"].Add(myModuleView);
}
}
这里是MyModuleView的内容:
<Grid>
<Grid.DataContext>
<vm:MyModuleVM/>
</Grid.DataContext>
<Button Content="My Module" Foreground="White" FontWeight="Bold" Command="{Binding Path=LaunchCommand}">
</Button>
</Grid>
视图模型,MyModuleVM:
class MyModuleVM : ObservableObject
{
protected IUnityContainer Container { get; private set; }
public MyModuleVM()
{
}
RelayCommand _launchCommand;
public ICommand LaunchCommand
{
get
{
if (_launchCommand == null)
{
_launchCommand = new RelayCommand(() => this.LaunchTestView(),
() => this.CanLaunchTestView());
}
return _launchCommand;
}
}
private void LaunchTestView()
{
TestView view = new TestView();
view.Title = "Test View";
var regionManager = Container.Resolve<IRegionManager>();
regionManager.Regions["MyWindowRegion"].Add(view);
}
private bool CanLaunchTestView()
{
return true;
}
}
所以我的计划如下:
创建实现 的IModule(MyModule的)类和具有初始化
当创建用于模块的视图模型 (MyModuleVM),把它装入一个 视图(MyModuleView)到壳体 它作为 壳
MyModuleVM显示的视图的 DataContext的包含在一个MyModuleView按钮 结合的命令。 当按钮被点击时, 命令被触发
现在,这里是我卡住的地方。使用 WindowRegionAdapter(一个适配器 ,帮助在 单独的窗口中创建视图)我想创建 并显示一个新的视图。如在 MyModuleVM中所见,LaunchTestView需要 才能访问该容器,以便将 添加到某个区域。我如何 应该到达容器?
而且我对访问容器的具体问题,如何当他们点击我的加入“小工具”添加到工具栏外壳和发射 意见的总体策略是什么?当谈到MVVM和Prism时,我是否会在这里失望?
谢谢你们。
嘿达米安。我的视图模型(需要访问容器)是通过视图的xaml创建的。我甚至会在哪写代码来调用container.Resolve或container.BuildUp? – Flack 2010-09-23 19:47:13
在这种情况下,您可以在新的MyModuleView()之后执行它(即:container.BuildUp(typeof(MyModuleVM),myModuleView)。DataContext);),但在这种情况下,通过ServiceLocator解析RegionManager可能也是一种好方法。 – 2010-09-23 19:58:56
嗯。如果我在MyModuleView myModuleView = new MyModuleView()之后添加BuildUp,它看起来像myModuleView.DataContext尚未创建。也许我正在讨论这个错误。这看起来像是一个简单的任务,我正在努力比它需要。我的方法是实现一个带有widget视图的工具栏,以启动其他视图?你知道讨论ServiceLocator的好资源吗? – Flack 2010-09-23 20:37:32