WPF Prism事件聚合器-订阅/发布事件
天下武功 一脉相承#
结合JS理解更容易理解:https://www.cnblogs.com/douyuanjun/p/17465402.html
跟uni.$on、uni.$off、uni.$once 和 uni.$emit 在 UniApp 中与 Prism 框架中的事件订阅和发布机制类似,可以说是相同的概念和原理。
MainWindow.xaml#
<Window x:Class="BlankApp1.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
WindowStartupLocation="CenterScreen"
Title="{Binding Title}" Height="350" Width="525" >
<Grid>
<StackPanel>
<Button FontSize="30" Command="{Binding OpenCommand}" Content="订阅"/>
<Button FontSize="30" Command="{Binding SendCommand}" Content="发布"/>
<TextBlock FontSize="30" Text="{Binding Title}"/>
</StackPanel>
</Grid>
</Window>
ViewModels/MainWindowViewModel#
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System.ComponentModel.Design;
using System.Windows;
namespace BlankApp1.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainWindowViewModel(IEventAggregator eventAggregator)
{
//订阅
OpenCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived);
//事件过滤器
/**
eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived,ThreadOption.PublisherThread,false,msg =>
{
if (msg.Equals("hello_")) return true;
else
return false;
});
**/
});
//发布
SendCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Publish("hello_ok");
});
//取消订阅
UnCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageReceived);
});
}
public void OnMessageReceived(string message)
{
Title += message + "\r\n";
}
public DelegateCommand OpenCommand { get; set; }
public DelegateCommand SendCommand { get; set; }
public DelegateCommand UnCommand { get; set; }
}
public class MessageEvent : PubSubEvent<string>
{
}
}
作者:douyuanjun
出处:https://www.cnblogs.com/douyuanjun/p/17788957.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具