我正在使用MVVM和Microsoft Prism libraries
进行WPF项目。因此,当我需要通过类进行通信时,我使用类Microsoft.Practices.Prism.MefExtensions.Events.MefEventAggregator
并发布事件和订阅方法,如下所示:
要发布:
myEventAggregator.GetEvent<MyEvent>().Publish(myParams)
要订阅:
myEventAggregator.GetEvent<MyEvent>().Subscribe(MySubscribedMethod)
但我的问题是:有没有办法在发布事件后从"订阅方法"返回一些数据?
我所知,如果所有事件订阅者都使用 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);
}
}
然后不是从CompositePresentationEvent
派生MyEvent
,而是从SynchronousEvent
派生它,这将保证您将同步调用该事件并且您将获得修改后的EventArgs
。