您的位置:首页 > 其它

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

2017-07-10 12:37 513 查看
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间传递参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐