简体   繁体   中英

How can I create new instance of window from ViewModel with Unity?

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:

EDIT:

To answer Wills questions

  1. I want to achieve this without any addons or plugins as I'm not familiar with any of those and most of the answers refering to some addons. Also, I feel it will be really handy for me if I make it work myself that gives me full control over it.
  2. I tried this but unable to make it work. Also, it was not clear on where i have to put what (either in view or vm)
  3. I don't want to open multiple 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.
  4. I just want to open multiple instance of window with different datacontext instance, It can be either from view or vm but it should maintain MVVM.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM