SendMessge中通过MessageSentEvent发布Payload,这里Payload一定要匹配MessageSentEvent的Payload类型,上面我们继承PubSubEvent<string>时使用的String,不然的话,这在编译的时候就会抛出异常。
private void SendMessage() { _ea.GetEvent<MessageSentEvent>().Publish(Message); }接下来,我们让ModuleB中的MessageListViewModel获取这个Payload,并进行一些操作:
using Prism.Events; using Prism.Mvvm; using System.Collections.ObjectModel; using UsingEventAggregator.Core; namespace ModuleB.ViewModels { public class MessageListViewModel : BindableBase { IEventAggregator _ea; private ObservableCollection<string> _messages; public ObservableCollection<string> Messages { get { return _messages; } set { SetProperty(ref _messages, value); } } public MessageListViewModel(IEventAggregator ea) { _ea = ea; Messages = new ObservableCollection<string>(); _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived); } private void MessageReceived(string message) { Messages.Add(message); } } }代码阅读:
private ObservableCollection<string> _messages; public ObservableCollection<string> Messages { get { return _messages; } set { SetProperty(ref _messages, value); } }这是 <ListBox ItemsSource="{Binding Messages}" /> 中的Messages,他的类型是ObservableCollection,具体为什么是 ObservableCollection而不是List!后面再说。
public MessageListViewModel(IEventAggregator ea) { _ea = ea; Messages = new ObservableCollection<string>(); _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived); }这里订阅了MessageSentEvent,并且处理Payload,处理Payload的方法是MessageReceived,这个方法在Messages新增一条记录。
事件聚合器可以有多个发布者和多个订阅者。