Daniel
Daniel

Reputation: 318

MVVM ViewModel-View communication

I have a ListView and a Popup which content(Buttons, TextBoxes etc.) changes dynamically depending what is selected in the ListView. Is it legal, if the View determines what is in the Popup or the ViewModel should do it? I also would like to ask, whether the View can handle the ViewModel's events?

Upvotes: 1

Views: 247

Answers (2)

Filip Skakun
Filip Skakun

Reputation: 31724

MVVM is not a law - it is a tool. If what you are doing serves your purpose - it works for you. If you are asking what the best practice is - it depends on why you using MVVM in the first place.

  • Is it because you want to write tests independent of the view? Then put your logical state in the view model.

  • Is it because you want to be able to display design time data in Blend? Then put your logical state in the view model and define design time data to show in design mode.

  • Is it because you want to have maintainable code that will be maintained for a long time by people familiar with MVVM? Put your logic in the view model.

  • Is it because your app is complicated and you would like to have separation of concerns so different people would work on the view and different people would work on the view model. Put your logic in the view model.

If none of these apply - you might be just fine and spend less time trying to figure it out by just putting the code in code behind and not let MVVM to be a drag.

If your problem is how to drive the contents of your Popup with your view model - you can typically do that using a combination of ItemsControls such as ListView, GridView or maybe a custom one and ContentControls with ItemTemplateSelectors or ContentTemplateSelectors that implement the logic of determining which view to display based on the view model state.

Also check my Minimalistic MVVM manifesto post.

Upvotes: 2

Eric Scherrer
Eric Scherrer

Reputation: 3388

Check out 5: Implementing the MVVM Pattern for a detailed explanation of what is valid in the View. It explains it a lot better than I could here in this answer.

I will give a shot at your questions though:

Q: Is it legal, if the View determines what is in the Popup or the ViewModel should do it? A: The view should determine how the Popup is displayed, the ViewModel should determine what is displayed.

Q: Can the View can handle the ViewModel's events? A: Absolutely, this is a key part of DataBinding - handling INotifyPropertyChanged events.

Upvotes: 1

Related Questions