【问题标题】:How to return data from a subscribed method using EventAggregator and Microsoft Prism libraries如何使用 EventAggregator 和 Microsoft Prism 库从订阅的方法返回数据
【发布时间】:2012-06-30 12:39:31
【问题描述】:

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

发布:

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

订阅:

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

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

【问题讨论】:

    标签: wpf events mvvm prism eventaggregator


    【解决方案1】:

    据我所知,如果所有事件订阅者都使用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&lt;T&gt;),它会覆盖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

    【讨论】:

    • 谢谢你的回复,我明白你的意思,我通过EventArgs返回数据,它可以工作。只是为了记录,我无法创建SyncronousEvent 类,因为方法SubscriptionToken 不是virtual。但是你的问题对我很有帮助。
    • @Dante 你不是覆盖SubscriptionToken,而是Subscribe 方法(它是虚拟的)。
    • 对不起,我的错,我在谈论 Subscribe 不是虚拟的方法,我现在正在查看它,如果我尝试编译你的示例 VS2010 告诉我该方法不是virtual。无论如何,您的解决方案正是我想要的,谢谢
    • @Dante 我在代码中使用的特定重载是不可覆盖的。我已经修改了我的答案以使用正确的重载,这绝对是虚拟的:)
    • Prism 6 将 CompositePresentationEvent 更改为 PubSubEvent stackoverflow.com/q/34668759/2122718
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多