您的位置:首页 > 移动开发

Event Aggregator in Prism (Composite Application Guidance for WPF)

2013-11-22 15:46 561 查看
The EventAggregator service is primarily a container for events that allow decoupling of publishers and subscribers so they can evolve independently. This decoupling is useful in modularized applications because new modules can be added that respond to events defined by the shell or, more likely, other modules.

In the Composite Application Library, EventAggregator allows subscribers or publishers to locate a specific EventBase. The event aggregator also allows for multiple publishers and multiple subscribers, as shown below.



The EventAggregator class is offered as a service in the container and can be retrieved through the IEventAggregator interface. The event aggregator is responsible for locating or building events and for keeping a collection of the events in the system.

public interface IEventAggregator
{
TEventType GetEvent<TEventType>() where TEventType : EventBase;
}


1) Let's get started with example below, at first we have to add refreences to namespaces below,

using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;


2) Event declaration and Initialization

public class MyStringEvent : CompositePresentationEvent<string> { }
public class MyIntEvent : CompositePresentationEvent<int> { }


IEventAggregator eventAggregator = new EventAggregator();
SubscriptionToken stringToken = new SubscriptionToken();
SubscriptionToken integerToken = new SubscriptionToken();


3) Event Subscription

stringToken = eventAggregator.GetEvent<MyStringEvent>().Subscribe(s => MessageBox.Show("this is " + s));
integerToken = eventAggregator.GetEvent<MyIntEvent>().Subscribe(i => MessageBox.Show("this is " + i.ToString()));


4) Event Publication

eventAggregator.GetEvent<MyStringEvent>().Publish("MyString");
eventAggregator.GetEvent<MyIntEvent>().Publish(1000);


5) Event unsubscription

eventAggregator.GetEvent<MyStringEvent>().Unsubscribe(stringToken);
eventAggregator.GetEvent<MyIntEvent>().Unsubscribe(integerToken);


To get more details, you can refer to : http://www.codeplex.com/wikipage?ProjectName=CompositeWPF&title=Getting%20Started&referringTitle=Home
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: