Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM Clarification: What belongs into ViewModel, what belongs into Model?

Tags:

mvvm

So I was looking into MVVM again after some time where I didn't really follow new developments and I noticed that the amount of tutorials/guides etc. has grown greatly. However most examples/example implementations of MVVM lack to explain something that's not really clear to me. All of these examples are pretty simple and none of them reads something form a database/file/etc.

Now for example I have some paint-like application and I save the paintings in XAML. What belongs into the ViewModel what belongs into the Model?

Does the Model supply functions to load/save the paintings from/to a XAML file?

Does the ViewModel bind to properties that the Model exposes (Color, Width, Position etc.)?

Does the validation happen in the Model or in the ViewModel?

like image 663
chrischu Avatar asked Feb 17 '10 19:02

chrischu


1 Answers

The ViewModel is the representation of the model which is suitable for the presentation technology you're using.

In your example I believe the Model would not provide the functions to load/save the paintings from/to a XAML file. This would be performed in a Data Access Object/Repository which would be called upon by the ViewModel taking Model instances as input. This bit is often variable though and depends on what your Model classes look like.

The ViewModel itself usually doesn't make use of data binding. It simply exposes the Model to the View in a way which is helpful for the the presentation (View) technology. In the case of WPF/Silverlight that basically means it implements the INotifyPropertyChanged interface.

Validation is usually initiated by the View (like pretty much everything), performed in the ViewModel but often delegated by the ViewModel to the Model. Of course it is best not to repeat your validations throughout your application. The best place for common validations is the Model (refer to IDataErrorInfo). However validations which are specific to your ViewModel can be handled directly in the ViewModel.

like image 177
b-rad Avatar answered Sep 18 '22 15:09

b-rad