I working with WPF application and using MVVM pattern for that. I'm having two separate project for view and viewmodel.
Added reference of Unity
in view and I'm using Unity
to inject my instance of MainWindowViewModel
to MainWindow
view on StartUp
of app and able to bind the viewmodel to view.
Now, I want to open the new instance of MainWindow
on clicking the button on the MainWindow
view.
Problem is how to create the an instance of view from Viewmodel.
Already tried the following:
To answer Wills questions
MainWindow
, this is just a R&D for the another work. In real scenario, we need to show status of some device attached with the systems and there will be separate Window
for each device attached. Even, if we can open mutiple childwindow from Mainwindow
, I'm ok with that. This is how I use to do it:
Having a central place for navigation. Could be the App.xaml.cs or you could have you own. In this class you would have your IoC container and control the Window.
You could then use a Messenger system to communicate between ViewModels and ViewModels to the application. MVVM Light Toolkit has a light-weight model for this. There are other MVVM frameworks/tools out there. PRISM is Microsoft's own, but can be complicated to start with. In PRISM this Messenging mechanism is called EventAggregator.
The ViewModel should have an ICommand
to handle the button click (See RelayCommands in MVVM Light Toolkit). The command sends a message which the application is listening to and opens up a new Window.
Soudo code:
public class App
{
public void InitializeMessengerHooks()
{
messenger.Subscribe(typeof(OpenWindowMessage), m => OpenWindow());
}
}
public class ViewModel
{
public void OpenWindow()
{
messenger.Send(new OpenWindowMessage());
}
}
Rough idea of how it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.