IEventAggregator 是一个事件聚合器,用于在不同模块之间进行通信。它允许模块之间进行解耦,通过发布和订阅事件来实现通信。
在使用 WPF prism IEventAggregator 时,你可以创建自定义事件,订阅事件并在需要时发布事件。这样可以实现模块之间的松耦合,提高代码的可维护性和可扩展性。
消息需要继承PubSubEvent
/// <summary> /// 消息事件PubSubEvent<可以是值类型也可以是引用类型> /// </summary> public class MessageEvent : PubSubEvent<MessageModel> { } public class MessageModel { /// <summary> /// 模块 /// </summary> public string Filter { get; set; } /// <summary> /// 内容 /// </summary> public string Message { get; set; } }
聚合器方法
/// <summary> /// 事件聚合器方法 /// </summary> public static class MessagerExtensions { /// <summary> /// 订阅 /// </summary> /// <param name="aggregator">事件聚合器</param> /// <param name="action"></param> /// <param name="filterName"></param> public static SubscriptionToken ResgiterMessager(this IEventAggregator aggregator, Action<MessageModel> action, string filterName) { return aggregator.GetEvent<MessageEvent>().Subscribe(action, ThreadOption.PublisherThread, true, (p) => { return p.Filter.Equals(filterName); }); } /// <summary> /// 发布 /// </summary> /// <param name="aggregator">事件聚合器</param> /// <param name="filterName">模块</param> /// <param name="messager">内容</param> public static void SendMessager(this IEventAggregator aggregator, string filterName, string messager) { aggregator.GetEvent<MessageEvent>().Publish(new MessageModel() { Filter = filterName, Message = messager }); } /// <summary> /// 取消订阅 /// </summary> /// <param name="aggregator">事件聚合器</param> /// <param name="subscriptionToken">订阅类型</param> public static void UnsubscribeMessager(this IEventAggregator aggregator, SubscriptionToken subscriptionToken) { aggregator.GetEvent<MessageEvent>().Unsubscribe(subscriptionToken); } }
使用:
//订阅事件 EventAggregator.ResgiterMessager(loginAtion, ViewNames.LoginView); private void loginAtion(MessageModel obj) { if(IsHardwareInitialized) { NavigationParameters keyValues = new NavigationParameters(); keyValues.Add("IndexViewKey", $"你好,现在时间{DateTime.Now.ToString("yyyy-MM-dd")}"); ModuleManager.LoadModule(ModuleName.MainModuleProfile);//加载 RegionManager.RequestNavigate(ContentControlName.MainWindowReginName, ViewNames.MainView, keyValues);//导航 } else { PrismProvider.Dispatcher.Invoke(() => { //加载硬件初始化模块 PrismProvider.ModuleManager.LoadModule(ModuleName.InitializesModuleProfile); //导航到主区域 PrismProvider.RegionManager.RequestNavigate(ContentControlName.MainWindowReginName, ViewNames.InitializesView); }); } }
当发布消息的时候会执行loginAtion方法
_eventAggregator.SendMessager(ViewNames.LoginView, "登入成功");//发布
标签:IEventAggregator,聚合,string,aggregator,Prism,事件,public From: https://www.cnblogs.com/MingQiu/p/18012743