How do I access the base object / model ViewModel

We are developing a WPF / MVVM application that allows the user to search and process contact records.

We have a MainViewModel that contains an observable collection of ContactViewModel objects, each of which wraps the Contact object returned from our business layer. The user interface displays them in a list, and the SelectedItem property is associated with the corresponding SelectedContact property in MainViewModel.

We will also have a button or something where the command is bound to the ICommand ProcessContact opened by MainViewModel.

ProcessContact should accept the selected contact and do something with it, it doesn't really matter.

My question is: what would be the correct way to access the base Contact object wrapped by the selected ContactViewModel? I could just open the Contact property in my view model, but that means the view can potentially bind properties directly to the model.

I found myself looking at instances of the ViewModel very often, which seems wrong when what I really want is the entity that it wraps.

Am I missing something obvious?

Edit: several suggestions thrown by colleagues:

  • Present the object as a protected property in the ViewModel, which will stop the view from binding to it (if the presentation classes are in a separate assembly)

  • Do not try to fully access the model. If we want to somehow process the underlying object, we call the method in the ViewModel. In my example, we can have a .Process method with ContactViewModel. ('SelectedContact.Process ())

The second option seems to be the best solution for me, but I'm not sure if we should embed this logic in the ViewModel (but if not, then where?)

+4
source share
3 answers

Your second sentence seems to me more correct. Usually, I transfer my data to a view model, which is like a controller anyway ... It should control what happens to your data using user actions in the view. So I would go with a wrapper of your data, and then attach the appropriate behaviors to your presentation model. I don’t know why you will worry about adding too much logic to your presentation model, that is, to its work!

+1
source

I suggest having an observable collection of Contact objects in your MainViewModel. The Framework automatically supports notification of changes to the properties of an entity, and you do not even have to embed INotifyPropertyChanged in your entity.

If you have any specific reason for wrapping your Contact object in the viewmodel (I'm curious to know them), you will have to open the Contact object (via the property) and use it.

0
source

Do not put your model in your ViewModel. At least do not publish it as public property.

You can make your presenter a model observer so that he is notified when the model has changed. Then your Moderator can call View and pass it the ViewModel .

0
source

All Articles