网址:https://www.cnblogs.com/ryzen/p/12610249.html

本文将介绍如何在.NET Core3环境下使用MVVM框架Prism的使用事件聚合器实现模块间的通信

一.事件聚合器#

 在上一篇 .NET Core 3 WPF MVVM框架 Prism系列之模块化 我们留下了一些问题,就是如何处理同模块不同窗体之间的通信和不同模块之间不同窗体的通信,Prism提供了一种事件机制,可以在应用程序中低耦合的模块之间进行通信,该机制基于事件聚合器服务,允许发布者和订阅者之间通过事件进行通讯,且彼此之间没有之间引用,这就实现了模块之间低耦合的通信方式,下面引用官方的一个事件聚合器模型图:

二.创建和发布事件#

1.创建事件#

 首先我们来处理同模块不同窗体之间的通讯,我们在PrismMetroSample.Infrastructure新建一个文件夹Events,然后新建一个类PatientSentEvent,代码如下:
PatientSentEvent.cs:

Copy
public class PatientSentEvent: PubSubEvent<Patient>
{
}

2.订阅事件#

 然后我们在病人详细窗体的PatientDetailViewModel类订阅该事件,代码如下:
PatientDetailViewModel.cs:

Copy
 public class PatientDetailViewModel : BindableBase
{
IEventAggregator _ea;
IMedicineSerivce _medicineSerivce; private Patient _currentPatient;
//当前病人
public Patient CurrentPatient
{
get { return _currentPatient; }
set { SetProperty(ref _currentPatient, value); }
} private ObservableCollection<Medicine> _lstMedicines;
//当前病人的药物列表
public ObservableCollection<Medicine> lstMedicines
{
get { return _lstMedicines; }
set { SetProperty(ref _lstMedicines, value); }
} //构造函数
public PatientDetailViewModel(IEventAggregator ea, IMedicineSerivce medicineSerivce)
{
_medicineSerivce = medicineSerivce;
_ea = ea;
_ea.GetEvent<PatientSentEvent>().Subscribe(PatientMessageReceived);//订阅事件
} //处理接受消息函数
private void PatientMessageReceived(Patient patient)
{
this.CurrentPatient = patient;
this.lstMedicines = new ObservableCollection<Medicine>(_medicineSerivce.GetRecipesByPatientId(this.CurrentPatient.Id).FirstOrDefault().LstMedicines);
}
}

3.发布消息#

 然后我们在病人列表窗体的PatientListViewModel中发布消息,代码如下:
PatientListViewModel.cs:

Copy
public class PatientListViewModel : BindableBase
{ private IApplicationCommands _applicationCommands;
public IApplicationCommands ApplicationCommands
{
get { return _applicationCommands; }
set { SetProperty(ref _applicationCommands, value); }
} private List<Patient> _allPatients;
public List<Patient> AllPatients
{
get { return _allPatients; }
set { SetProperty(ref _allPatients, value); }
} private DelegateCommand<Patient> _mouseDoubleClickCommand;
public DelegateCommand<Patient> MouseDoubleClickCommand =>
_mouseDoubleClickCommand ?? (_mouseDoubleClickCommand = new DelegateCommand<Patient>(ExecuteMouseDoubleClickCommand)); IEventAggregator _ea; IPatientService _patientService; /// <summary>
/// 构造函数
/// </summary>
public PatientListViewModel(IPatientService patientService, IEventAggregator ea, IApplicationCommands applicationCommands)
{
_ea = ea;
this.ApplicationCommands = applicationCommands;
_patientService = patientService;
this.AllPatients = _patientService.GetAllPatients();
} /// <summary>
/// DataGrid 双击按钮命令方法
/// </summary>
void ExecuteMouseDoubleClickCommand(Patient patient)
{
//打开窗体
this.ApplicationCommands.ShowCommand.Execute(FlyoutNames.PatientDetailFlyout);
//发布消息
_ea.GetEvent<PatientSentEvent>().Publish(patient);
} }

效果如下:

4.实现多订阅多发布#

 同理,我们实现搜索后的Medicine添加到当前病人列表中也是跟上面步骤一样,在Events文件夹创建事件类MedicineSentEvent:

MedicineSentEvent.cs:

Copy
 public class MedicineSentEvent: PubSubEvent<Medicine>
{ }

 在病人详细窗体的PatientDetailViewModel类订阅该事件:
PatientDetailViewModel.cs:

Copy
 public PatientDetailViewModel(IEventAggregator ea, IMedicineSerivce medicineSerivce)
{
_medicineSerivce = medicineSerivce;
_ea = ea;
_ea.GetEvent<PatientSentEvent>().Subscribe(PatientMessageReceived);
_ea.GetEvent<MedicineSentEvent>().Subscribe(MedicineMessageReceived);
} /// <summary>
// 接受事件消息函数
/// </summary>
private void MedicineMessageReceived(Medicine medicine)
{
this.lstMedicines?.Add(medicine);
}

 在药物列表窗体的MedicineMainContentViewModel也订阅该事件:
MedicineMainContentViewModel.cs:

Copy
public class MedicineMainContentViewModel : BindableBase
{
IMedicineSerivce _medicineSerivce;
IEventAggregator _ea; private ObservableCollection<Medicine> _allMedicines;
public ObservableCollection<Medicine> AllMedicines
{
get { return _allMedicines; }
set { SetProperty(ref _allMedicines, value); }
}
public MedicineMainContentViewModel(IMedicineSerivce medicineSerivce,IEventAggregator ea)
{
_medicineSerivce = medicineSerivce;
_ea = ea;
this.AllMedicines = new ObservableCollection<Medicine>(_medicineSerivce.GetAllMedicines());
_ea.GetEvent<MedicineSentEvent>().Subscribe(MedicineMessageReceived);//订阅事件
} /// <summary>
/// 事件消息接受函数
/// </summary>
private void MedicineMessageReceived(Medicine medicine)
{
this.AllMedicines?.Add(medicine);
}
}

在搜索Medicine窗体的SearchMedicineViewModel类发布事件消息:
SearchMedicineViewModel.cs:

Copy
 IEventAggregator _ea;

 private DelegateCommand<Medicine> _addMedicineCommand;
public DelegateCommand<Medicine> AddMedicineCommand =>
_addMedicineCommand ?? (_addMedicineCommand = new DelegateCommand<Medicine>(ExecuteAddMedicineCommand)); public SearchMedicineViewModel(IMedicineSerivce medicineSerivce, IEventAggregator ea)
{
_ea = ea;
_medicineSerivce = medicineSerivce;
this.CurrentMedicines = this.AllMedicines = _medicineSerivce.GetAllMedicines();
} void ExecuteAddMedicineCommand(Medicine currentMedicine)
{
_ea.GetEvent<MedicineSentEvent>().Publish(currentMedicine);//发布消息
}

效果如下:

然后我们看看现在Demo项目的事件模型和程序集引用情况,如下图:

 我们发现PatientModule和MedicineModule两个模块之间做到了通讯,但却不相互引用,依靠引用PrismMetroSample.Infrastructure程序集来实现间接依赖关系,实现了不同模块之间通讯且低耦合的情况

三.取消订阅事件#

 Prism还提供了取消订阅的功能,我们在病人详细窗体提供该功能,PatientDetailViewModel加上这几句:
PatientDetailViewModel.cs:

Copy
 private DelegateCommand _cancleSubscribeCommand;
public DelegateCommand CancleSubscribeCommand =>
_cancleSubscribeCommand ?? (_cancleSubscribeCommand = new DelegateCommand(ExecuteCancleSubscribeCommand)); void ExecuteCancleSubscribeCommand()
{
_ea.GetEvent<MedicineSentEvent>().Unsubscribe(MedicineMessageReceived);
}

效果如下:

四.几种订阅方式设置#

 我们在Demo已经通过消息聚合器的事件机制,实现订阅者和发布者之间的通讯,我们再来看看,Prim都有哪些订阅方式,我们可以通过PubSubEvent类上面的Subscribe函数的其中最多参数的重载方法来说明:

Subscribe.cs:

Copy
public virtual SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<TPayload> filter);

1.action参数#

其中action参数则是我们接受消息的函数

2.threadOption参数#

ThreadOption类型参数threadOption是个枚举类型参数,代码如下:
ThreadOption.cs

Copy
public enum ThreadOption
{
/// <summary>
/// The call is done on the same thread on which the <see cref="PubSubEvent{TPayload}"/> was published.
/// </summary>
PublisherThread, /// <summary>
/// The call is done on the UI thread.
/// </summary>
UIThread, /// <summary>
/// The call is done asynchronously on a background thread.
/// </summary>
BackgroundThread
}

三种枚举值的作用:

  • PublisherThread:默认设置,使用此设置能接受发布者传递的消息
  • UIThread:可以在UI线程上接受事件
  • BackgroundThread:可以在线程池在异步接受事件

3.keepSubscriberReferenceAlive参数#

默认keepSubscriberReferenceAlive为false,在Prism官方是这么说的,该参数指示订阅使用弱引用还是强引用,false为弱引用,true为强引用:

  • 设置为true,能够提升短时间发布多个事件的性能,但是要手动取消订阅事件,因为事件实例对保留对订阅者实例的强引用,否则就算窗体关闭,也不会进行GC回收.
  • 设置为false,事件维护对订阅者实例的弱引用,当窗体关闭时,会自动取消订阅事件,也就是不用手动取消订阅事件

4.filter参数#

 filter是一个Predicate的泛型委托参数,返回值为布尔值,可用来订阅过滤,以我们demo为例子,更改PatientDetailViewModel订阅,代码如下:
PatientDetailViewModel.cs:

Copy
  _ea.GetEvent<MedicineSentEvent>().Subscribe(MedicineMessageReceived,
ThreadOption.PublisherThread,false,medicine=>medicine.Name=="当归"|| medicine.Name== "琼浆玉露");

效果如下:

C# prism 框架 MVVM框架 Prism系列之事件聚合器的更多相关文章

  1. .NET Core 3 WPF MVVM框架 Prism系列之事件聚合器

    本文将介绍如何在.NET Core3环境下使用MVVM框架Prism的使用事件聚合器实现模块间的通信 一.事件聚合器  在上一篇 .NET Core 3 WPF MVVM框架 Prism系列之模块化 ...

  2. 从PRISM开始学WPF(六)MVVM(三)事件聚合器EventAggregator?

    从PRISM开始学WPF(一)WPF? 从PRISM开始学WPF(二)Prism? 从PRISM开始学WPF(三)Prism-Region? 从PRISM开始学WPF(四)Prism-Module? ...

  3. 从PRISM开始学WPF(七)MVVM(三)事件聚合器EventAggregator-更新至Prism7.1

    原文:从PRISM开始学WPF(七)MVVM(三)事件聚合器EventAggregator-更新至Prism7.1 事件聚合器EventAggregator [7.1updated]除了app部分,没 ...

  4. 从PRISM开始学WPF(七)MVVM(三)事件聚合器EventAggregator?

    原文:从PRISM开始学WPF(七)MVVM(三)事件聚合器EventAggregator? 从PRISM开始学WPF(一)WPF? 从PRISM开始学WPF(二)Prism? 从PRISM开始学WP ...

  5. Prism的IEventAggregator事件聚合器, 事件订阅发布, ViewModel之间的通讯

    WPF中时常会遇到ViewModel之间的通讯,ViewModel并不知道自己的View,但是一个View发生的更改需要通知另外一个View. 举一个例子,软件界面上有个人信息,打开一个界面更改用户的 ...

  6. ENode框架Conference案例分析系列之 - 事件溯源如何处理重构问题

    前言 本文可能对大多数不太了解ENode的朋友来说,理解起来比较费劲,这篇文章主要讲思路,而不是一上来就讲结果.我写文章,总是希望能把自己的思考过程尽量能表达出来,能让大家知道每一个设计背后的思考的东 ...

  7. 【DDD-Apwork框架】事件总线和事件聚合器

    第一步:事件总线和事件聚合器 [1]事件总线 IEventBus IUnitOfWork.cs using System; using System.Collections.Generic; usin ...

  8. .NET Core 3 WPF MVVM框架 Prism系列文章索引

    .NET Core 3 WPF MVVM框架 Prism系列之数据绑定 .NET Core 3 WPF MVVM框架 Prism系列之命令 .NET Core 3 WPF MVVM框架 Prism系列 ...

  9. .NET Core 3 WPF MVVM框架 Prism系列之模块化

    本文将介绍如何在.NET Core3环境下使用MVVM框架Prism的应用程序的模块化 前言  我们都知道,为了构成一个低耦合,高内聚的应用程序,我们会分层,拿一个WPF程序来说,我们通过MVVM模式 ...

随机推荐

  1. 盘点linux操作系统中的10条性能调优命令,一文搞懂Linux系统调优

    原文链接:猛戳这里 性能调优一直是运维工程师最重要的工作之一,如果您所在的生产环境中遇到了系统响应速度慢,硬盘IO吞吐量异常,数据处理速度低于预期值的情况,又或者如CPU.内存.硬盘.网络等系统资源长 ...

  2. python 元组推导式

    >>> b=(page for page in range(10))>>> print(b)<generator object <genexpr> ...

  3. 微信小程序云开发-云存储的应用-识别行驶证

    一.准备工作 1.创建云函数identify 2.云函数identify中index.js代码 1 // 云函数入口文件 2 const cloud = require('wx-server-sdk' ...

  4. 【Lucas组合数定理】组合-FZU 2020

    组合 FZU-2020 题目描述 给出组合数C(n,m), 表示从n个元素中选出m个元素的方案数.例如C(5,2) = 10, C(4,2) = 6.可是当n,m比较大的时候,C(n,m)很大!于是x ...

  5. C#曲线分析平台的制作(三,三层构架+echarts显示)

    本文依据CSDN另一位网友关于三层构架的简单搭建,基于他的源码进行修改.实现了三层构架合理结构,以及从数据库中传递数值在echarts显示的实验目的. 废话不多说,show me codes: 具体构 ...

  6. Redis(6379)未授权访问

    环境搭建 打开kali终端 输入命令 wget http://download.redis.io/releases/redis-3.2.0.tar.gz tar xzf redis-3.2.0.tar ...

  7. SQL语句(一)基础查询与过滤数据

    目录 一.数据库测试表 二.基础查询 1. 获得需要的记录的特定字段 2. 查询常量值 3. 查询表达式 4. 查询函数 5. 起别名 6. 去重 7. CONCAT函数的简单使用 三.过滤数据 大纲 ...

  8. Calcite(一):javacc语法框架及使用

    是一个动态数据管理框架. 它包含许多组成典型数据库管理系统的部分,但省略了存储原语.它提供了行业标准的SQL解析器和验证器,具有可插入规则和成本函数的可自定义优化器,逻辑和物理代数运算符,从SQL到代 ...

  9. 攻防世界misc——János-the-Ripper

    攻防世界misc---János-the-Ripper 附件题目,题目的文件名为:misc100. 下载后,拖入linux中,binwalk发现有隐藏文件.用"strings  János- ...

  10. “入职一年,那个被高薪挖来的Android开发被劝退了。”

    其实,在很多小伙伴的想法中,是希望通过跳槽实现薪酬涨幅,可是跳槽不是冲动后决定,应该谨慎啊~ 01 我的学弟,最近向我吐槽,2020 年上半年入职一家公司,当时是高薪挖走的他,所谓钱到位,工作也是充满 ...