6

MVVM と を使用して、WPF プロジェクトに取り組んでいMicrosoft Prism librariesます。したがって、クラスを介して通信する必要がある場合は、クラスを使用し、Microsoft.Practices.Prism.MefExtensions.Events.MefEventAggregator以下のようにイベントを発行してメソッドをサブスクライブします。

公開するには:

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

購読するには:

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

しかし、私の質問は次のとおりです。イベントを発行した後、「サブスクライブされたメソッド」からデータを返す方法はありますか??

4

1 に答える 1

14

私の知る限り、すべてのイベントサブスクライバーが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);
    }
}

次に、から派生する代わりに、から派生MyEventCompositePresentationEventますSynchronousEvent。これにより、イベントが同期的に呼び出され、変更されたが取得されることが保証されますEventArgs

于 2012-06-28T23:24:35.993 に答える