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;
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); }); } }
分类:
C#中的事件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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吧