Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM: Decouple Model from ViewModel

I've just started learning WPF MVVM using Prism and Unity. Decoupling the view from the viewmodel works pretty well, but I don't get how wire up my viewmodel and my model. I doesn't feel right to just create a new EntityObject right in my viewmodel. I have already skim-read the WAF BookLibrary sample but it is quite bulky and adds a lot of extra stuff around the essential part (binding between view and viewmodel), and the Prism docs don't say a word (as far as I read it) about viewmodel - model interaction.

Does anyone know a good source that explains how to use viewmodel and model in a clean way or can me give some advise?

Best Regards

Jay

like image 632
Jay Avatar asked Jul 08 '11 20:07

Jay


1 Answers

Everyone will have their own opinions on this. Personally I don't mind using the model directly in the view model. For me, the whole idea of a view model is to extend your model in such a way that it can be consumed by a view.

A simple example of this would be person object, It would have model properties like like name and age for instance. When I get to the view model stage I may add properties to it like visibility which would not make sense on the model proper.

Another point to note is I would consider a model to be the data and the view model to be the context. So you may have a "Card" View Model for a person but you may also have a "List Item" view model that represents the same model in a different context, with different view model specific properties.

I do tend to make my models up using interfaces where relevant and use Inversion of control to inject them into the view model, that way the only thing my view model actually knows is that it needs an IPerson and that it will be provided in the constructor.

As I said other people will have different ideas, all are correct and its up to you to work out which one suits your needs.

like image 133
deanvmc Avatar answered Nov 09 '22 07:11

deanvmc