Prism 框架中使用IEventAggregator事件聚合器简单实现ViewModel之间的通讯

xiaoxiao2021-02-28  88

1.在项目中添加EventAggregator类库,添加EventAggregatorRepository类和GetInputMessages类。 using Microsoft.Practices.Prism.PubSubEvents; using Microsoft.Practices.Prism.Regions; using System; namespace EventAggregatorPratice { public class EventAggregatorRepository { public EventAggregatorRepository() { eventAggregator = new EventAggregator(); } public IEventAggregator eventAggregator; public static EventAggregatorRepository eventRepository = null; //单例,保持内存唯一实例 public static EventAggregatorRepository GetInstance() { if (eventRepository == null) { eventRepository = new EventAggregatorRepository(); } return eventRepository; } } } using Microsoft.Practices.Prism.PubSubEvents; namespace EventAggregatorPratice { public class GetInputMessages : PubSubEvent<string> { } }

其中EventAggregatorRepository提供事件聚合实例,GetInputMessages为定义的事件类型。

2.订阅事件

添加对EventAggregator的引用,在XXViewModel初始化时订阅

public void SetSubscribe() { EventAggregatorRepository .GetInstance() .eventAggregator .GetEvent<GetInputMessages>() .Subscribe(ReceiveMessage, ThreadOption.UIThread, true); } public void ReceiveMessage(string messageData) { //dosomething } public XXViewModel() { InitializeComponent(); SetSubscribe(); } 3.发布事件

在其他ViewModel中添加对EventAggregato的引用,发布事件

public static void Print(string Meesage) { EventAggregatorRepository .GetInstance() .eventAggregator .GetEvent<GetInputMessages>() .Publish(Meesage); } 以上就能实现不同ViewModel间传递参数

转载请注明原文地址: https://www.6miu.com/read-21391.html

最新回复(0)