Q:

Best practices for opening a new window with WPF MVVM pattern

I've been wondering about this for a while... What's the best practice for opening a new window (view & viewmodel) from another viewmodel IF we keep in mind that the viewmodel which opens the new window is not aware of the existence of that view (as it should be).
Thanks.

A:

I prefer to use an action delegate that is inserted via the ViewModel constructor. this also means we can easily verify during unit-testing:
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        DataContext = new MainViewModel(() => (new Window()).Show()); // would be actual window
    }
}

public class MainViewModel
{
    private Action popupAction;
    public MainViewModel(Action popupAction)
    {
        this.popupAction = popupAction;
    }

    public ICommand PopupCommand { get; set; }

    public void PopupCommandAction()
    {
        popupAction();
    }
}

public class SomeUnitTest
{
    public void TestVM()
    {
        var vm = new MainViewModel(() => { });
    }
}

A:

I don't use the ViewModel to open another View/ViewModel. This is in the responsibility of a Controller. The ViewModel can inform the Controller (e.g. via Event) that the user expects to see the next View. The Controller creates the View/ViewModel with the help of an IoC Container.
How this works is shown in the ViewModel (EmailClient) sample application of the WPF Application Framework (WAF).

A:

Use the mediator pattern such as mvvmlight's messenger class:
http://mvvmlight.codeplex.com/Thread/View.aspx?ThreadId=209338
The basic idea is the viewmodel sends a message to its view.  The receiving view then looks like this:
OnMsgRecived() {

  Viewmodel vm = New Viewmodel() - Or use dependency injection to resolve

  View v = new View()
  v.DataContext = vm
  v.Show()
}

This allows the viewmodel that sent the message to show another window with no 'knowledge' of how or who did the opening.

