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

Asked

Viewed 361 times

2

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

But now I have a problem, I need to open a new window on the system, and who would be this responsibility?

We know that in the "perfect world" of MVVM, Viewmodel should not communicate with View, but how can I open a window without Viewmodel’s knowledge of View?

I’m about to break this "rule" and open a new window the same way I do in Windows Forms, but that would impact automated testing and go against the MVVM principle, so what’s the solution? It’s only worth breaking that rule?

1 answer

2


I will not give my opinion if it is worth breaking the rule or not, even because here in the OS is not a place to keep giving a lot of opinion. I’ll give you an alternative not to break the rule.

Make an interface to encapsulate the View and Jete in 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"))
            .....
    }
}
  • I know that Stack is not a place for opinions, but in the comments we can talk about it. I think your solution circumvents the problem, but it’s a bit of a hassle to have to manually add the windows, especially when it comes to a large application. Even so you answered correctly, because the Viewmodel was not connected directly with the View.

  • Complementing what I wrote about it. I also have this problem with the display of Dialogs (Messagebox)

  • 1

    Really, it’s a lot of work, but it doesn’t have much of a way out. It either follows the concept to the letter, or it slips away. Msgbox is the same thing, you have to create an interface and inject into the VM.

  • Thanks for the information, really the work is bigger, as I intend to work with small teams, I think that MVVM would not be very suitable at certain times.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.