Reputation: 2393
In the MVVM Pattern, is there exactly one ViewModel per View or is there exactly one ViewModel per Model?
Upvotes: 26
Views: 12949
Reputation: 4239
Theoretically, relationships are
View n - 1 ViewModel n - 1 Model
I know, a lot of people will bite and beat me, but... In practice...
Very often, in business applications, there is data access layer (DAL). And very often entities from DAL are your Models. Sometimes you should wrap those entities with additional classes to provide extended functionality or maybe some additional properties. Maybe you have your own Models...
ViewModels and Views (in practice) usually have 1 to 1 relationship. Something like - every screen (or part of screen) is actually a paired View and ViewModel. I think usually just something like - View is UI layer and ViewModel is code-behind level. View is just XAML file - presentation layer. And (the best practice) everything else should be in ViewModel - all data receiving processes, all commands, all changable fields etc. This way you can usually test ViewModel (with unit testing). One ViewModel can have several Views (in practice) usually only when you have shared ViewModels for, for example, DesktopApplication (WPF), Web Application (Silverlight) and Windows Phone. Something like this. But usually - one ViewModel - one View. If you have several Views for one ViewModel - usually you will have a lot of maintaince problems...
Upvotes: 33
Reputation: 2618
It is possible to use more than one view for the same view model and it is also possible to use to many different view models for the same view.
Many-Views to one-ViewModel:
For example in a master-detail arrangement you could put your view models into an ObservableCollection and present them in a ListBox in which you bind the items display to the Title property of the ViewModel. The ListBox present one view of your view models. Then the ListBox.SelectedItem is bound to a different view which present the details of the selected model.
One-View to many-ViewModels:
Starting with a set of view models that all share common property names you could present all the view models in the same view. For example you could have a simple view model consisting of a Title property and a ModelValue property. In all the view models the Title property would be string but each different view model could have a different data type for the ModelValue property. The StringViewModel would have a string ModelValue and the DoubleViewModel would have a double ModelValue. The presentation of the different view models could share the same view consisting of a TextBlock to present the Title and a TextBox to edit the ModelValue. This would work for any type editable in a TextBox.
By mixing and matching Views and ViewModels you can gain great advantage from a clean separation of Views and ViewModels.
Upvotes: 5
Reputation: 184326
There is one model per viewmodel and one viewmodel per view, in the other direction everything is n.
Upvotes: 8