MVVM Design – Should ViewModel or View Create New Views?

cdesignmvvmwpf

In my WPF application, I want to create a new view. Where should I do that – in ViewModel or Model?

The application is a (very simple for now) one-window form-like tool with single "send" button. In case if one of checkboxes is selected, new window using the same ViewModel should pop up to ask user for some additional details. For the purposes of this question, let's consider just the new window approach without considering another approaches like shown/hidden panel.

Ideally, in View there shouldn't be any code. In addition, as View does not have any logic in it VM would initially need to check if creating new view is needed, and – when it is – bouncing this responsibility back to View, leading to code bloat.

On the other hand, creating a new view in ViewModel violates principle that ViewModel shouldn't know anything about View.

So, is it better to create new views in View or ViewModel?

Best Answer

I use dependency injection and a IViewFactory injected into the view model to respect both constraints.

A ProductViewModel (for example) calls this.viewFactory.Show("Details", this) to open ProductDetailsView with itself as ProductViewModel. It could also open a view based on another view model with this.viewFactory.Show<ClientViewModel>().

The implementation (there are actually several for WinForms, simple Wpf Windows, a Wpf shell with tabs,...) is based on a StructureMap convention. The views designate their view model via an IView<ProductViewModel> interface.

So the view model doesn't know anything about the view except its role (default view, details view, ...), and the view contains no code to create another view. Also, the view models are in a separate assembly which doesn't reference any Wpf assembly.