WPF using MVVM - Whose responsibility is it to open a new window?

2

In MVVM we have Views, ViewModels and Models. All the business logic of my application is in models, where I use viewModels to manage them, as well as binds and commands that are sent from Views.

But now I have a problem, I need to open a new window in the system, and whose responsibility would it be?

We know that in the MVVM's "perfect world", ViewModel should not communicate with View, but how can I open a window without ViewModel being unaware of View?

I'm about to break this "rule" and open a new window the same way I do in Windows Forms, however this would impact on automated testing and would go against the MVVM principle, so what's the solution? Is it okay to break this rule?

    
asked by anonymous 06.02.2017 / 17:18

1 answer

2

I'm not going to give my opinion if it's worth breaking the rule or not, because here in the SO is not a place to be giving much opinion. I'll give you an alternative not to break the rule.

Make an interface to encapsulate the View and inject into the ViewModel.

public interface IView
{
    // no lugar de string poderia ser um enumerador também
    bool Show(string viewName);
}

public class ViewManager : IView
{
    public bool Show(string viewName)
    {
        if (viewName == "ListaUsuarios")
        {
            new ListaUsuarios().Show();
            return true;
        }

        return false;
    }
}

public class ViewModel
{
    private IView _viewManager;
    public ViewModel(IView viewManager)
    {
        _viewManager = viewManager;
    }

    public void AbrirView()
    {
        if(_viewManager.Show("ListaUsuarios"))
            .....
    }
}
    
06.02.2017 / 18:03