ViewModel to ViewModel Communication

Chris Swain picture Chris Swain · Jan 26, 2011 · Viewed 8.1k times · Source

Given the following scenario:

  1. ViewModelA launches ViewModelB (via a common Controller, of course, that uses Ioc and DI to resolve the types needed).
  2. ViewModelB needs to set a property value in ViewModelA.

Is it bad to simply inject ViewModelA into ViewModelB via constructor injection and just set the property directly?

Or…

Should a messaging system like the EventAggregator from Prism be used to handle all communication between ViewModels?

I like the injection approach because it’s easy, but my instincts are telling me I’m missing something. I call on your collective wisdom to help fill in my blind spot.

Answer

Mark Seemann picture Mark Seemann · Jan 26, 2011

I consider it a code smell if you need two-way references. Often you can replace one of the references with an event.

Let ViewModelB raise an event that ViewModelA subscribes to. A complete messaging system like the one found in Prism is certainly an option, but in your scenario it sounds like a 'normal' event will do just fine.