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

时间:2012-06-28 22:53:22

标签: wpf events mvvm prism eventaggregator

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

发布:

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

订阅:

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

但我的问题是:有没有办法在发布活动后从“订阅的方法”中返回一些数据?

1 个答案:

答案 0 :(得分:12)

据我所知,如果所有事件订阅者都使用ThreadOption.PublisherThread选项(也是默认选项),则事件同步执行,订阅者可以修改EventArgs对象,所以你可以在出版商那里

myEventAggregator.GetEvent<MyEvent>().Publish(myParams)
if (myParams.MyProperty)
{
   // Do something
}

订阅者代码如下所示:

// 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;
}

如果您知道应始终同步调用事件,则可以为事件(而不是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);
    }
}

然后从MyEvent派生CompositePresentationEvent,而不是从SynchronousEvent派生,这将保证您将同步调用该事件,并且您将获得修改后的{{1} }}