我有一個看起來像工具欄的外殼,並定義了我的主要區域(一個包裝面板)。我需要做的是能夠將小部件添加到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