Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for opening a new window with WPF MVVM pattern

Tags:

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.

like image 579
Jens Avatar asked Nov 24 '10 11:11

Jens


2 Answers

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(() => { });
    }
}
like image 143
Dean Chalk Avatar answered Oct 09 '22 00:10

Dean Chalk


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).

like image 33
jbe Avatar answered Oct 09 '22 01:10

jbe