My questions are:
- Can/Should a
ViewModelsupport multipleViews? - Can/Should a
Viewbe supported by multipleViewModels? ( 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.
Here is my view on this –
Yes, same ViewModel can be used with multiple views; e.g. say you have a
CustomerViewModelhaving details of a customer and some commands, you can use this ViewModel with a view having aDataGridto display all the customers(so anObservableCollection<CustomerViewModel>will be used) and also use the same ViewModel with a view having a form to edit the details of a single customer.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?