AGB
AGB

Reputation: 2448

WPF MVVM - How to arrange ViewModels

I am working on a WPF application based on the MVVM pattern.

For a particular entity I have a Model containing the entity properties, a ViewModel which implements INotifyPropertyChanged and has some additional logic as well as exposing the properties of the Model and two Views, one for creating and one for editing the entity.

I create a single ViewModel for the edit and create Views and pass through an id for the entity when it is an edit so that the existing data can be retrieved.

What I can't work out is how to structure the ViewModels in this situation, namely:

  1. Should I have an EntityViewModel as a property of an EditEntityViewModel where the EntityViewModel exposes the properties of the Model and the EditEntityViewModel handles the commands and other logic? If I do this then I don't think the EntityViewModel is notified of changes in the View.
  2. Should I have two separate ViewModels who know nothing about each other?
  3. Should I have a single ViewModel for the page which exposes the properties of the Model as well as handling the commands and other logic?
  4. Something else?

I know that I should have one ViewModel per View but I'm not entirely sure how to define what a separate view is. You can probably tell that I'm a bit confused as to how exactly to implement the framework.

Many thanks for any help.

Upvotes: 0

Views: 310

Answers (1)

Big Daddy
Big Daddy

Reputation: 5224

Don't over complicate it. Try to keep your view-model to model relationship 1:1. As a result, your view-model will expose methods to support all CRUD methods on the model. Also, consider using one view, not two. There's a lot of overlap between them, so I think it makes sense. You'll have fewer classes to write and maintain. I think #3 on your list, using the one view approach, is your best option.

Upvotes: 1

Related Questions