C#事件の事件聚合器(二)

WPF中时常会遇到ViewModel之间的通讯,ViewModel并不知道自己的View,但是一个View发生的更改需要通知另外一个View。

举一个例子,软件界面上有个人信息,打开一个界面更改用户的信息后,这时显示个人信息的地方理应发生变化。此场景下更改用户后应该通知另一个显示用户信息的区域去更新。一般在设计时,我们会设计成一个个的用户控件,用户控件的数据来源于ViewModel,所以此时需要ViewModel之间通讯。

介绍场景后,我们利用Prism的IEventAggregator事件聚合器来实现。

首先在项目中引用下列Prism组件:

Microsoft.Practices.Prism

Microsoft.Practices.Prism.UnityExtensions

Microsoft.Practices.ServiceLocation

Microsoft.Practices.Unity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.Events;
///   
/// 自定义事件——用户信息更改事件  
///   
public class UserChangedEvent : CompositePresentationEvent {  
} 

2.订阅事件,结合上述场景应该在显示个人信息的地方订阅

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.ServiceLocation;
using System.ComponentModel;
using System.Windows;
 
IEventAggregator eventAggregator;  
SubscriptionToken token;  
  
///   
/// 构造方法  
///   
public RightContainerViewModel() {  
    //设计时状态判断  
    if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") {   
        return;   
    }  
  
    //获取事件聚合器  
    eventAggregator = ServiceLocator.Current.GetInstance();  
    //订阅事件  
    token=eventAggregator.GetEvent().Subscribe(UserChanged);    
  
}  
  
//事件触发  
public void UserChanged(User user) {  
    CurrentUser = user;  
    if (token != null) {  
        //取消订阅事件  
        eventAggregator.GetEvent().Unsubscribe(UserChanged);  
    }  
}

3.发布事件,结合上述场景应该在更新用户信息的地方

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.ViewModel;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.ServiceLocation;
private IEventAggregator eventAggregator;  
///   
/// 构造方法  
///   
public LeftContainerViewModel() {  
    //设计时状态判断  
    if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") {  
        return;  
    }  
    //获取事件聚合器  
    this.eventAggregator = ServiceLocator.Current.GetInstance();  
}  
  
///   
/// 按钮命令  
///   
public ICommand UpdateCommand {  
    get {  
        return new DelegateCommand(() => {  
            //发布事件  
            eventAggregator.GetEvent().Publish(CurrentUser);  
        });  
    }  
} 
原文地址:https://www.cnblogs.com/xietianjiao/p/7521788.html