所谓的潇洒

导航

事件聚合器

1.定义事件  

  public class MessageEvent : PubSubEvent<String>
  { }

2.发布和订阅  

        private readonly IEventAggregator _eventAggregator;
        //构造函数添加事件聚合器参数
        public ViewAViewModel(IEventAggregator eventAggregator)
        {            
            this._eventAggregator = eventAggregator;
            PubCmd = new DelegateCommand(() => { 
                eventAggregator.GetEvent<MessageEvent>().Publish("pub"); //发布
            });
            SubCmd = new DelegateCommand(() => {
                //eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageRecieved);//简单订阅

                //订阅过滤器
                eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageRecieved, ThreadOption.PublisherThread,false, msg =>
                {
                    if (msg != "hello") return true;
                    else return false;
                });

                //eventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageRecieved);//取消订阅
            });
        }

        public void OnMessageRecieved(string msg)
        {
            Message += msg + "\r\n";
        }

 

posted on 2023-03-19 18:42  所谓的潇洒  阅读(40)  评论(0编辑  收藏  举报