0
votes

I am trying to create a WPF application by using WPF and PRISM. I am also using MEF and mvvm. Is it possible to have 2 viewmodels that can communicate to each other by using the event aggregastor? Eg. Publish in viewmodel A and subscribe in Viewmodel B? And if so how? I have build a program with multiple viewmodels and some of these viewmodels should communicate with each other, but somehow if I publish in Viewmodel A using a eventaggregator, A subscribe in viewmodel B will never be recognized to belong to the same eventaggregator so that I cannot update my View connected to viewmodel B.

5

5 Answers

1
votes

This is the basic key steps to define Event Aggregator

(1) Create Event Agg..

public class YourEvent: CompositePresentationEvent {

}

(2) Publisher vm

eventAggregator.Get().Publish(object);

(3) Subscription Vm

YourEvent eventobj = eventAggregator.Get();

    if (subscriptionToken != null)
    {
        eventobj.Unsubscribe(subscriptionToken);
    }

    subscriptionToken = eventobj.Subscribe(YourEventHandler, ThreadOption.UIThread, false, yourfun);
0
votes

The only possibility is that ViewModel "B" is not loaded or has not subscribed to the event yet. If this is not true, I suggest you to paste some snippets.

0
votes

Are you subscribing using a WeakReference (a weak subscription)? If so, and your subscriber isn't referenced elsewhere, it may be getting garbage collected and disappearing before you publish the event.

0
votes

The EventAggregator is always the same, you have to pass it of each Viewmodel. Prism and MEF can do this for you:

  1. you can load EventAggregator in the constructor by using Unity of PRISM

  2. you can inject a reference of EventAggregator with MEF

0
votes

Do you have an instance of both ViewModel "B" and ViewModel "A"? Are you publishing the event before the subscription code has run? Are they both publishing/subscribing to the same Event?

EventAggregator.GetEvent(Of MyEventType).Subscribe(Sub()

                                                   End Sub)