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

来源:https://www.cnblogs.com/ryzen/archive/2020/01/16/12196619.html
-Advertisement-
Play Games

本文將介紹如何在.NET Core3環境下使用MVVM框架Prism的使用事件聚合器實現模塊間的通信 一.事件聚合器 在上一篇 ".NET Core 3 WPF MVVM框架 Prism系列之模塊化" 我們留下了一些問題,就是如何處理同模塊不同窗體之間的通信和不同模塊之間不同窗體的通信,Prism提 ...


本文將介紹如何在.NET Core3環境下使用MVVM框架Prism的使用事件聚合器實現模塊間的通信

一.事件聚合器

 在上一篇 .NET Core 3 WPF MVVM框架 Prism系列之模塊化 我們留下了一些問題,就是如何處理同模塊不同窗體之間的通信和不同模塊之間不同窗體的通信,Prism提供了一種事件機制,可以在應用程式中低耦合的模塊之間進行通信,該機制基於事件聚合器服務,允許發佈者和訂閱者之間通過事件進行通訊,且彼此之間沒有之間引用,這就實現了模塊之間低耦合的通信方式,下麵引用官方的一個事件聚合器模型圖:

二.創建和發佈事件

1.創建事件

 首先我們來處理同模塊不同窗體之間的通訊,我們在PrismMetroSample.Infrastructure新建一個文件夾Events,然後新建一個類PatientSentEvent,代碼如下:
PatientSentEvent.cs:

public class PatientSentEvent: PubSubEvent<Patient>
{
}

2.訂閱事件

 然後我們在病人詳細窗體的PatientDetailViewModel類訂閱該事件,代碼如下:
PatientDetailViewModel.cs:

 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:

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:

 public class MedicineSentEvent: PubSubEvent<Medicine>
 {

 }

 在病人詳細窗體的PatientDetailViewModel類訂閱該事件:
PatientDetailViewModel.cs:

 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:

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:

 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:

 private DelegateCommand _cancleSubscribeCommand;
 public DelegateCommand CancleSubscribeCommand =>
       _cancleSubscribeCommand ?? (_cancleSubscribeCommand = new DelegateCommand(ExecuteCancleSubscribeCommand));

  void ExecuteCancleSubscribeCommand()
  {
      _ea.GetEvent<MedicineSentEvent>().Unsubscribe(MedicineMessageReceived);
  }

效果如下:

四.幾種訂閱方式設置

 我們在Demo已經通過消息聚合器的事件機制,實現訂閱者和發佈者之間的通訊,我們再來看看,Prim都有哪些訂閱方式,我們可以通過PubSubEvent類上面的Subscribe函數的其中最多參數的重載方法來說明:

Subscribe.cs:

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

1.action參數

其中action參數則是我們接受消息的函數

2.threadOption參數

ThreadOption類型參數threadOption是個枚舉類型參數,代碼如下:
ThreadOption.cs

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:

  _ea.GetEvent<MedicineSentEvent>().Subscribe(MedicineMessageReceived,
ThreadOption.PublisherThread,false,medicine=>medicine.Name=="當歸"|| medicine.Name== "瓊漿玉露");

效果如下:

五.源碼

 最後,附上整個demo的源代碼:PrismDemo源碼


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • C#實現對Excel操作,根據數據的類型不同或者來源不同會放在不同的頁簽中,C#實現添加頁簽代碼如下:(path為文檔保存的地址,dt為要處理的源數據) public void addSheet(string Path, DataTable dt) { var SlDoc = new SLDocum ...
  • 1.ImportData主方法 把傳入為object數組類型,按照下標取出對應的參數,此處為Table和Username public object[] ImportData(object[] Param) { DataTable dt = (DataTable)Param[0]; string m ...
  • 實現把String字元串轉化為In後可用參數代碼: public string StringToList(string aa) { string bb1 = "("; if (!string.IsNullOrEmpty(aa.Trim())) { string[] bb = aa.Split(new ...
  • 本筆記摘抄自:https://www.cnblogs.com/PatrickLiu/p/7640873.html,記錄一下學習過程以備後續查用。 一、引言 很多人說原型設計模式會節省機器記憶體,他們說是拷貝出來的對象是原型的複製,不會使用記憶體。我認為這是不對的,因為拷貝出來的每一個對象都是實際 存在的 ...
  • ``` var xmlstr = @" some_appid 1413192605 component_verify_ticket some_verify_ticket "; Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i ...
  • 已有站點:HTTP80 %systemroot%\system32\inetsrv\APPCMD ADD APP /SITE.NAME:"HTTP80" /path:/Redirect /physicalPath:"C:\Windows\System32\drivers\etc" /applicat ...
  • 設計一個簡單的登錄視窗,要求輸入用戶名:小金,密碼:123456時候點登錄能正確轉到另一個視窗。 1、建立窗體應用。 2、這裡創建一個login和一個NewForm的窗體。 3、在login的窗體拖拉2個label和2個textbox和1個linklabel的控制項。一個標簽名字為用戶名,一個標簽為密 ...
  • Microsoft Visual Studio 2010 的項目為件改為Microsoft Visual Studio 2015預設打開 2010 的Solution (.Sln) file 更改為 2015 的Solution (.Sln) file ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...