MVVM duplicating Model properties in ViewModel

2019-04-07 12:56发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

Your ViewModel is incorrect. If you already have a Model of Product type, you can simply define something like this in your ViewModel: public Product Product {...}



标签: mvvm