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

2017-07-10 20:13:55来源:CSDN作者:yuligai100人点击


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间传递参数


最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台