MVVM框架 数据绑定 事件命令 发布订阅消息

1 2 3 4 5 6 7 8 9 | <StackPanel> <Button Command= "{Binding OpenCommand}" Content= "事件" /> <Button Command= "{Binding PublishCommand}" Content= "发布消息" /> <Button Command= "{Binding CancelSubscribeCommand}" Content= "取消订阅" /> <TextBlock DockPanel.Dock= "Bottom" Text= "{Binding Message}" HorizontalAlignment= "Center" VerticalAlignment= "Center" /> </StackPanel> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | using Prism.Commands; using Prism.Events; using Prism.Mvvm; namespace ModuleA.ViewModels { public class ViewAViewModel : BindableBase { //继承 BindableBase 基类, 实 MVVM 数据绑定,事件命令,消息发布和订阅 private readonly IEventAggregator m_EventAggregator; //发布订阅消息聚合器 private string _message; public string Message { get { return _message; } set { SetProperty( ref _message, value); } //双向数据绑定 } public ViewAViewModel(IEventAggregator eventAggregator) { Message = "Prism ModuleA" ; m_EventAggregator = eventAggregator; //订阅 MessageEvent 类型的消息 //1.普通订阅 //m_EventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived); //2.过滤订阅,只订阅 Title=”新闻“ 的消息。 m_EventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived, ThreadOption.PublisherThread, false , msg => { if (msg.Title.Equals( "新闻" )) return true ; //接收消息 else return false ; //拒绝接收 }); OpenCommand = new DelegateCommand(() => { Message = "OpenCommand" ; }); PublishCommand = new DelegateCommand(() => { //发布消息 MessageEntity entity = new MessageEntity { Title = "新闻" , Description = "发布了一条新闻!" , }; m_EventAggregator.GetEvent<MessageEvent>().Publish(entity); }); CancelSubscribeCommand = new DelegateCommand(() => { //取消订阅 m_EventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageReceived); }); } public void OnMessageReceived(MessageEntity entity) { //处理订阅消息 Message = $ "{entity.Title}:{entity.Description}" ; } public DelegateCommand PublishCommand { get ; private set ; } public DelegateCommand OpenCommand { get ; private set ; } //点击事件,命令 public DelegateCommand CancelSubscribeCommand { get ; private set ; } } /// <summary> /// 定义消息类型 /// </summary> public class MessageEvent : PubSubEvent<MessageEntity> { } /// <summary> /// 消息实体类 /// </summary> public class MessageEntity { public string Title { get ; set ; } public string Description { get ; set ; } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现