Search code examples
prismeventaggregator

Prism event aggregator in common user control


In my wpf application I have several user controls, one of them is a TreeView for selection of a particular data type. When selectedItem changes, I publish a selectionChanged event (using Prism's EventAggregator) and a subscriber will get this event. So far, so good.

Now, I start to use the same user control in a new view, actuall in a new window. When selectionChanged event is fired from the new window, both subscriptions are triggered. I would like to specify the sender of the event, so that the subscriber can check who the event is intended for. There are many ways I can do this, but I none that I like so far.

So the question goes out to you guys, how can I achieve this?


Solution

  • The simplest way to achieve this would be to add the sender to your published event args.

    public class SelectionChangedEventArgs
    {
        public object Sender { get; set; }
    
        // Other properties (e.g. SelectedItem, etc.)
    }
    

    Then as you said, you could easily check the sender to know whether you should handle the event. Prism already provides such a feature, with the following overload of Subscribe:

    public virtual SubscriptionToken Subscribe(Action<TPayload> action,
                                               ThreadOption threadOption,
                                               bool keepSubscriberReferenceAlive,
                                               Predicate<TPayload> filter);
    

    So you can actually provide a filter that checks the Sender property when subscribing, so your handler will only be called when this condition is met.