Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a ViewModel in MVVM reference the View?

In the MVVM (Model-View-ViewModel) pattern should the ViewModel reference the view. I would think that it should not. But how should the following scenario be handeled? I have a view that has a tab control as the main container, the viewmodel for this view implements a command to add a new tab to the tab control. The easy way would be to allow the viewmodel to reference the view and then in the command implementation to just programmatically add the new tab to the tabcontrol in the view. This just seems wrong. Should I somehow bind the tabcontrol to the viewmodel and then implement a data/control-template to add the new tabs. I hope this makes some kind of sense to somebody :)

like image 634
Johan Avatar asked Sep 08 '10 18:09

Johan


People also ask

Can a ViewModel reference a view?

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

Should each view have its own ViewModel?

It is not necessary for any view to have a view model to function. However, Google recommends the pattern because it leads to good design. If you want to say that your app is MVVM, then you need to keep the view separated from the data that drives it.

Do we have references of activity in ViewModel?

Almost all docs on Android documentation recommends that ViewModel should not have reference to the view of any sort that includes activity but this code lab takes the reference of activity in one of it's a method.

Should ViewModel know about model?

Models are just the plain data, and a ViewModel is something that acts like a padding in between the two, that it should get information from the Model and pass it onto the View, and the View should know how to present it.


1 Answers

In "pure" MVVM, the ViewModel shouldn't really reference the View. It's often convenient, however, to provide some form of interface in the View whereby the ViewModel can interact with it.

However, I've found that I almost never do that anymore. The alternative approach is to use some form of attached property or blend behavior within your View, and bind it to your ViewModel properties. This allows you to keep the View logic 100% within the View. In addition, by creating a behavior for this, you create a reusable type that can be used to handle this in every ViewModel->View interaction. I strongly prefer this approach over having any View logic within the ViewModel.

In order to demonstrate this technique, I wrote a sample for the Expression Code Gallery called WindowCloseBehavior. It demonstrates how you can use a Behavior within the View bound to properties in the ViewModel to handle controlling a Window's life-cycle, including preventing it from being closed, etc.

like image 64
Reed Copsey Avatar answered Oct 11 '22 06:10

Reed Copsey