Prism的事件聚合器
1、基础
Prism不同Module中的数据通讯可以通过事件聚合器IEventAggregator。我们先定义一个继承PubSubEvent的事件,如:
public class MessageSentEvent : PubSubEvent<string> { }
此时,此事件传递的就是string类型数据,我们在Module A中发布此事件,如:
public class MessageViewModel : BindableBase { IEventAggregator _ea; private string _message = "Message to Send"; public string Message { get { return _message; } set { SetProperty(ref _message, value); } } public DelegateCommand SendMessageCommand { get; private set; } public MessageViewModel(IEventAggregator ea) { _ea = ea; SendMessageCommand = new DelegateCommand(SendMessage); } private void SendMessage() { _ea.GetEvent<MessageSentEvent>().Publish(Message); } }
我们再在Module B中订阅事件,即可得到传过来的string,如:
IEventAggregator _ea; public MessageListViewModel(IEventAggregator ea) { _ea = ea; SubCommand = new DelegateCommand(SubEvent); } private void SubEvent() { _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived); } private void MessageReceived(string message) { Messages.Add(message); }
就可以得到传过来的字符串了
通过Unsubscribe可以取消订阅,则不再接受到string,除非再次订阅。
2、进阶
接受的字符亦可筛选,如:
_ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived, ThreadOption.PublisherThread, false, (filter) => filter.Contains("Brian"));
private void MessageReceived(string message)
{
Messages.Add(message);
}
则MessageReceived只会接收到包含Brian的字符串