Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel/View relationship and validation

Tags:

mvvm

wpf

In our WPF application we want to use the basic MVVM pattern. We were discussing it and some uncertainties about ViewModel/View relationship and validation came up. Would you say the following is a good understanding of it?

  • Every View has one and only one ViewModel and the ViewModel's purpose is to provide its View with data and handle all of its View's events and commands. (Are there instances where one ViewModel services two Views, e.g. a standard XAML input form view and a CSV Import which provides the same data as the form and thus needs to have the same validation?)

  • Validation is handled solely by the ViewModel when e.g. the view throws a ChangedFocus or SaveButtonPressed event, etc.

  • The Model is pretty dumb, simply being the data structure based on one or more tables from the database, but the model itself doesn't handle validation, for instance. It is even the ViewModel that builds up and holds the ObservableCollection of objects e.g. "Customers" and not the Model itself.

Any feedback appreciated.

like image 337
Edward Tanguay Avatar asked Apr 07 '09 11:04

Edward Tanguay


1 Answers

Every View has one and only one ViewModel

I think if you are strict about your following of the pattern then each view will have just one ViewModel. We have a case in our application where requirements changed mid-stream and it was easiest to have the View reference two different ViewModels. Depending on how you implement the pattern this may or may not be possible.

Are there instances where one ViewModel services two Views

Yes, this is one of the advantages of the pattern.

Validation is handled solely by the ViewModel

Not necessarily. We chose to have our model classes implement IDataErrorInfo and do the validation themselves. This insures that no matter where the Model class is used the validation will be the same. If the validation ever needs to change it is in just one place.

The Model is pretty dumb

It is only as dumb as you want it to be. You can include validation and business rules in the model if you like.

like image 143
John Myczek Avatar answered Sep 22 '22 10:09

John Myczek