gpt4 book ai didi

wpf - 如何使用EventAggregator和Microsoft Prism库从预订的方法返回数据

转载 作者:行者123 更新时间:2023-12-03 20:27:55 24 4
gpt4 key购买 nike

我正在使用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);
}
}

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

关于wpf - 如何使用EventAggregator和Microsoft Prism库从预订的方法返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11254032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com