I have a shell which looks like toolbar and defines my main region (a wrap panel). What I need to do is be able to add widgets to the shell and when a widget is clicked, a new window (view) is opened. Below is what I have so far:
I created a module class which adds a view to the main region:
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);
}
}
Here is the content of MyModuleView:
<Grid>
<Grid.DataContext>
<vm:MyModuleVM/>
</Grid.DataContext>
<Button Content="My Module" Foreground="White" FontWeight="Bold" Command="{Binding Path=LaunchCommand}">
</Button>
</Grid>
The view model, 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;
}
}
So my plan was as follows:
Create the class that implements IModule (MyModule) and have it load a view (MyModuleView) into the shell when initialized
Create a view model for the module (MyModuleVM) and set it as the DataContext of the view displayed in the shell
MyModuleVM contains a command that a button in MyModuleView binds to. When the button is clicked the command is triggered
Now, here is where I am stuck. Using a WindowRegionAdapter (an adapter that helps to create views in separate windows) I wanted to create and display a new view. As seen in MyModuleVM, LaunchTestView needs access to the container in order to add the view to a region. How am I supposed to get to the container?
Besides my specific question about accessing the container, how is my overall strategy of adding "widgets" to a toolbar shell and launching views when they are clicked? Am I comlpetely off track here when it comes to MVVM with Prism?
Thanks guys.
You can get the container injected through constructor or property injection. To do that, the ViewModel instance must be resolved by the container, or the BuildUp method should be called after it has been instantiated.
I hope this helps.
Thanks, Damian