Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a reference in a View to a ViewModel (which is its DataContext) in any way detrimental to MVVM pattern?

Let's say a ViewModel publishes an Event and a View which is using that VM as its DataContext subscribes to that Event by obtaining a reference to the VM by casting its DataContext to VM instance:

vm = DataContext as MainViewModel;
if (vm == null) return;
vm.SomeUIRelatedNotice += DoSomethingUIRelated;

The way I see this, the VM ramains decoupled and its testability is in no way affected, and the View already has a reference to the VM so I see no problem with this at all but I want to hear from the MVVM purists if they think this is bad design with negative impact on the MVVM pattern and if so why?

like image 938
Dean Kuga Avatar asked Jan 24 '14 21:01

Dean Kuga


1 Answers

As long as the view model is not performing any view logic itself, I don't consider this to be breaking the MVVM pattern.

It looks like in your case the view model is trying to interact and direct the view somehow, so you should probably know that there are other ways to achieve such behavior which are considered to be more pure MVVM:

  • MVVM Light Toolkit's Messenger service
  • Prism's EventAggregator or its interaction patterns
like image 93
Adi Lester Avatar answered Sep 28 '22 04:09

Adi Lester