Reputation: 12119
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?
Upvotes: 6
Views: 272
Reputation: 25201
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:
Messenger
serviceEventAggregator
or its interaction patternsUpvotes: 3
Reputation: 17380
View knowing a VM is not wrong at all and like you mentioned is perfectly fine.
In such cases, the question I ask myself is
"Would doing this X action make my VM's break testability? or hinder the scope of testability in my business logic?"
If answer is "Yes" - You're kind-of heading down the wrong path. If "No" go right ahead. In my opinion that's all there is to MVVM. It helps you unit test logic and classes which we couldnt before with things like MVC and tight coupling.
As you arent unit-testing view related stuff to a large extent, this wouldn't affect your MVVM "true-ness" in any way.
Side-Note
While I would stick with my above opinion. One thing is, have you considered using a Messenger
Simple Tutorial of MVVM Light's Messenger / EventAggregator
pattern. With a Messenger
pattern, your VM would be just publishing the Message's and you're Views could essentially just subscribe to these messages without even having to refer to the VM (make the message type custom strong if you want uniqueness). This way you do not have to do the whole casting from DataContext
and can also unit-test the Message publishing from the VM perfectly fine.
Upvotes: 2