如何使用EventAggregator和Microsoft Prism库从订阅方法返回数据

Dan*_*nte 5 wpf events prism mvvm eventaggregator

我正在使用MVVM和WPF项目Microsoft Prism libraries.所以,当我需要通过类进行通信时,我使用该类Microsoft.Practices.Prism.MefExtensions.Events.MefEventAggregator,我发布事件和订阅方法如下:

要发布:

myEventAggregator.GetEvent<MyEvent>().Publish(myParams)

认购:

myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod)

但我的问题是:有没有办法在发布事件后从"订阅方法"返回一些数据?

Adi*_*ter 13

据我所知,如果所有事件订阅者都使用该ThreadOption.PublisherThread选项(这也是默认选项),则事件同步执行,订阅者可以修改EventArgs对象,因此您可以在发布者中

myEventAggregator.GetEvent<MyEvent>().Publish(myParams)
if (myParams.MyProperty)
{
   // Do something
}
Run Code Online (Sandbox Code Playgroud)

订阅者代码如下所示:

// Either of these is fine.
myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod)
myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod, ThreadOption.PublisherThread)

private void MySubscribedMethod(MyEventArgs e)
{
    // Modify event args
    e.MyProperty = true;
}
Run Code Online (Sandbox Code Playgroud)

如果您知道应始终同步调用事件,则可以为事件(而不是CompositePresentationEvent<T>)覆盖该Subscribe方法创建自己的基类,并且只允许订阅者使用该ThreadOption.PublisherThread选项.它看起来像这样:

public class SynchronousEvent<TPayload> : CompositePresentationEvent<TPayload>
{
    public override SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<TPayload> filter)
    {
        // Don't allow subscribers to use any option other than the PublisherThread option.
        if (threadOption != ThreadOption.PublisherThread)
        {
            throw new InvalidOperationException();
        }

        // Perform the subscription.
        return base.Subscribe(action, threadOption, keepSubscriberReferenceAlive, filter);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,而不是派生MyEventCompositePresentationEvent,你得到它SynchronousEvent,它会向你保证,该事件将被同步调用,并且你会得到修正EventArgs.