Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM duplicating Model properties in ViewModel

Tags:

mvvm

It seems that there is a guidance that a model should not expose its entities to View, and that all required properties should be duplicated in ViewModel

Example:

Product
Id {get; set;}
Name {get; set;}
.......


ProductViewModel : ViewModelBase
Id {get; set;}
Name {get; set;}
.......

Why is this required? I can understand this if Model doesnt implement INPC, but if it does, then I find this quite unnecessary.

like image 524
Goran Avatar asked Jun 29 '12 13:06

Goran


3 Answers

When the View is bound to the Model:

  • If the View needs to change or you have multiple views a change to the Model will cause changes to all the Views bound to that Model.

  • From the View's perspective, the object it is bound to might not be that intuitive; when you need to add a properties and/or commands to the the object do you add those to the ViewModel and keep the 'original' properties in the Model or do you modify the Model?

Having a ViewModel gives you an extra abstraction between a single Model and multiple (versions of) Views

All in all it is just a guideline but be aware that what seems OK today might be not so great when you need to modify/update the application.

like image 189
Emond Avatar answered Nov 08 '22 19:11

Emond


Guidance, is just that. It depends on the situation at hand. Purists will argue that separating the model entirely from the view allows the model to change without the view changing.

I tend to only proxy model properties if I have to (either INPC or some view specific logic like the model has FirstName and LastName but no FullName)

Otherwise I bind to the Model (which is a public property on the ViewModel). If my situation changes and I need to encapsulate something then i refactor when I have a need.

I do always try to ensure there is a ViewModel in place (even if it only exposes the model) so refactoring is easier later.

like image 5
Adam Mills Avatar answered Nov 08 '22 19:11

Adam Mills


My question is, why are your models implementing INPC? Do they need to?

Usually models are just a DTO and don't need any change logic.

Also if your base implementation of INPC is coming from an MVVM framework, but your models exist in a shared assembly does that assembly then need a reference to your MVVM framework, and potentially other WPF assemblies too?

The scenario we had was a set of shared objects representing our data on both the server and the client side. Client side was a WPF app so that was fine but for the server side was a service, so we didn't need INPC.

like image 2
Cameron MacFarland Avatar answered Nov 08 '22 19:11

Cameron MacFarland