Prism里EventAggregator的事件订阅及发布

EventAggregator是一个对于便于管理事件的工具。

1. 定义一个类,继承自CompositePresentationEvent<T>。该类用来定义不同的事件及其参数和处理方式

public class GetInputMessages:CompositePresentationEvent<string>
{
}

2. 创建一个EventAgregator的实例,并且保证该实例唯一来管理事件

    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;
        }
    }
创建eventAggregator

3. 订阅事件(定义事件处理方式)

EventAggregatorRepository.GetInstance().eventAggregator.GetEvent<GetInputMessages>().Subscribe(ReceiveMessage,ThreadOption.UIThread,true);


//事件处理方式
public void ReceiveMessage(string messageData)
{
     this.txtResult.Text = messageData;
}
subscribe事件

4. 发布事件(调用事件处理)

EventAggregatorRepository.GetInstance().eventAggregator.GetEvent<GetInputMessages>().Publish(messageData);
publish事件

 

实现机制和委托(Delegate)非常类似,个人认为这样EventAggregator的存在只是为了让逻辑更加清楚而已吧。他的好处是如果处理方式一致的话,可以在多个页面来触发这样一个事件

 

转载于:https://www.cnblogs.com/Alf7/p/4220798.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Prism库提供了一种称为"dispatch"的机制,用于在UI线程上自动分发事件。通过使用Prism事件聚合器(EventAggregator)和订阅者模式,可以实现此功能。 在Prism中,发布者通过调用EventAggregator的Publish方法来引发事件订阅者可以通过在订阅期间指定ThreadOption.UIThread来自动在UI线程上接收事件。这意味着当事件发布时,订阅者的事件处理程序将在UI线程上执行,从而避免了在非UI线程上更新UI的问题。 以下是一个示例代码,演示了如何在Prism中使用dispatch机制: ```csharp // 发布者 public class TickerSymbolSelectedEvent : PubSubEvent<string> { } public class MainPageViewModel { private readonly IEventAggregator _eventAggregator; public MainPageViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; } public void PublishEvent(string message) { _eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish(message); } } // 订阅者 public class MainWindowViewModel { public MainWindowViewModel(IEventAggregator eventAggregator) { eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Subscribe(ShowNews, ThreadOption.UIThread); } private void ShowNews(string message) { MessageBox.Show(message); } } ``` 在上面的示例中,MainPageViewModel是一个发布者,它通过调用EventAggregator的Publish方法来引发TickerSymbolSelectedEvent事件。MainWindowViewModel是一个订阅者,它通过调用EventAggregator的Subscribe方法来订阅TickerSymbolSelectedEvent事件,并在订阅期间指定ThreadOption.UIThread,以确保ShowNews方法在UI线程上执行。 通过使用Prism的dispatch机制,可以方便地在Prism应用程序中处理UI线程上的事件分发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值