1

My questions are:

  1. Can/Should a ViewModel support multiple Views ?
  2. Can/Should a View be supported by multiple ViewModels? ( I believe answer to this question is Yes).

What is the best practice for such a situation where for a relatively small module you have relatively small view(s). So, in that situation should we create multiple ViewModels for each view or shall we use a single ViewModel to serve all the view(s) within the same module. Note: number of views within the smaller module is restricted to 5-6.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
nishantcop
  • 977
  • 1
  • 8
  • 24

2 Answers2

1

Here is my view on this -

  1. Yes, same ViewModel can be used with multiple views; e.g. say you have a CustomerViewModel having details of a customer and some commands, you can use this ViewModel with a view having a DataGrid to display all the customers(so an ObservableCollection<CustomerViewModel> will be used) and also use the same ViewModel with a view having a form to edit the details of a single customer.

  2. It depends, but generally No. A view can depend on multiple ViewModels if it comprises of multiple views; say, a single Window having multiple views. e.g. A dashboard having list of customers, a form to add a new customer, a section to display products etc.; but even in this case it's always better to create a single parent ViewModel which will contain instances of other sub view models.

    I always prefer to have one ViewModel for a single view and try to design my application that way.

But yes it all depends on the application and how you design your views and viewmodels. In MVVM you first design your Models and ViewModels based on business logic and then use them with your views.

Also have a look at this similar question - ViewModel per View or per Model?

Community
  • 1
  • 1
akjoshi
  • 15,374
  • 13
  • 103
  • 121
0

It depends. If for example you have a model containing a series of observation you can have the same serving two view, one with a chart and one with a grid. I mean you have different views of the same conceptual model. In the case the view is a page fragmented with subviews with different things is better to have for all these part a specific viewmodel serving them. As a personal experience I had in the past an articulated view served by a single model and I wasn't satisfied by that, you eventually come in a situation when the view model code becames too complex and eventually a refactor is needed.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115