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);  
        });  
    }  
} 
复制代码

 

posted @   卖雨伞的小男孩  阅读(688)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示