WPF 如何设置全局的订阅发布事件

文章目录

前言

我们需要一个全局事件订阅发布功能,实现页面通讯。使两个毫无关系的页面通过一个中间量进行通讯。

代码

IEventAggregator:消息订阅集合

这个是Prism提供的消息订阅功能。使用如下

设置订阅类型,即关键字

java 复制代码
PubSubEvent<>,<>里面存放的是订阅的数据类型,推荐使用元祖
///
public class EventClass : PubSubEvent<string>
{

}

官方案例,在ViewModel中使用

java 复制代码
private readonly IEventAggregator eventAggregator;
 public string MyTitle { get; set; }
 public ViewAViewModel(IEventAggregator eventAggregator)
 {
     
     //通过Prism注入得到
     this.eventAggregator = eventAggregator;

	//订阅
     eventAggregator.GetEvent<EventClass>().Subscribe(res =>
     {
         Debug.WriteLine(res.ToString());
     });
     //推送
	 eventAggregator.GetEvent<EventClass>().Publish("我是侧边栏传来的值:事件通知");
 }

Tips:订阅中传递的值和EventClass: PubSubEvent<string> 中<>设置的类型有关。

但是经过我的测试,好像不能跨页面进行通讯。

逻辑修改

java 复制代码
    public partial class App
    {
    	//在App.xaml中进行声明
        public static IEventAggregator EventAggregator { get;set; } = new EventAggregator();
        
    }

对应每个xxxView页面,都定义一个xxxViewEvent。

在每个ViewModel的构造函数中订阅自己的ViewEvent,这样别的页面直接对该Event进行推送即可达到路由传值。通过key,value的形式对返回值进行解析。

演示事例

java 复制代码
public ViewAViewModel(IEventAggregator eventAggregator)
        {
            
            App.EventAggregator.GetEvent<ViewAEvent>().Publish("我是ViewModel传来的值");

            App.EventAggregator.GetEvent<ViewAEvent>().Subscribe(res =>
            {
                Debug.WriteLine(res.ToString());
                MyTitle = res;
            });
        }

总结

Prism和WPF给了我们很多的解决方案,但是其实我们只需要最简单又好用的解决方案即可。有了页面通讯,完全不需要路由通讯了。直接在页面跳转完成之后再页面通讯即可。统一而又优雅的解决方案才是我们需要的。

相关推荐
happyprince14 小时前
11-Hugging Face Transformers 分布式与并行系统深度分析
分布式·c#·wpf
加号316 小时前
【WPF】 基于 Canvas 读取并渲染 DXF 文件的技术指南
c#·wpf
AC赳赳老秦19 小时前
用 OpenClaw 整理团队技术分享:自动提取 PPT 内容、生成文字稿、同步到知识库
开发语言·python·自动化·powerpoint·wpf·deepseek·openclaw
闪电悠米1 天前
黑马点评-秒杀优化-03_blocking_queue_async_order
数据库·分布式·oracle·junit·wpf·lua
kingwebo'sZone1 天前
WPF 在(WrapPanel父级使用可以自动换行)每个 TextBlock 显示一行数据(竖排,垂直)
wpf
闪电悠米2 天前
黑马点评-秒杀优化-02_lua_precheck
开发语言·redis·分布式·缓存·junit·wpf·lua
FuckPatience2 天前
WPF 获取一个控件某个依赖属性的默认绑定方式
wpf
加号32 天前
【WPF】 ListView 数据绑定:从列表呈现到复杂交互的完整实践
wpf·交互
闪电悠米2 天前
黑马点评-Redisson-01_why_redisson
java·服务器·网络·数据库·缓存·wpf
小满Autumn2 天前
CommunityToolkit.Mvvm 架构笔记:现代 MVVM、源生成器与工程化实践
笔记·架构·c#·.net·wpf·mvvm