ViewModel to ViewModel Communication

Given the following scenario:

  • ViewModelA launches ViewModelB (through a common controller, of course, which uses Ioc and DI to resolve the required types).
  • ViewModelB you must set the value of the property in ViewModelA.

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

Or...

Should a messaging system such as Prism's EventAggregator be used to handle all communication between ViewModels?

I like the injection approach because it is easy, but my instincts tell me that I missed something. I urge your collective wisdom to help fill my blind spot.

+4
source share
4 answers

I suggest you read this question (and my answer) as it is similar, but not quite to your problem. It deals with communicating properties between parent / child ViewModel objects.

Let's look at a basic example:

  • ViewModelA is parent and must present Sum of some property on B
  • ViewModelB is a child and has a property that requires summation

Thus, the user makes a request to edit the property on B, and the request is successful, so B supposedly changes the value of his property and fires the PropertyChanged event.

ViewModelA can subscribe to events for all children, but, going this way, I do not like it. When children are added and removed, you have a lot of bookkeeping.

Putting A into B is cleaner, but you still have a lot of bookkeeping. What to do if you have the action “Clear children” on A? You must remember that you need to get rid of the parental relationship from B to A in all cases. Nevertheless, this is better than the events, in my opinion, because they are more pronounced.

Personally, I like the idea of ​​messaging. I am more familiar with MVVM Light messenger than with Prism, but this is the same idea ... a global message bus. Anytime, any B can say: "I changed my property!" and then A listens for the notification and calculates itself. I think this is your cleanest solution with much less bookkeeping.

+1
source

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

Let ViewModelB raise an event that is signed by ViewModelA. A complete messaging system like the one found in Prism is certainly an option, but in your scenario it sounds like a “normal” event, which will be great.

+2
source

You can find sample WPF Application Framework (WAF) applications. ViewModels do not know about each other. Mediation between them is carried out by controllers . This way you can prevent circular dependencies between ViewModel objects.

0
source

I suggest using a much lighter, dedicated Messaging solution called “ Light Message Bus .” This is not part of any other ;-) MVVM framework, but an independent component. And I earned it instantly in less than 3 minutes.

0
source

Source: https://habr.com/ru/post/1337167/


All Articles