学海无涯

导航

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

 

<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>

  

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; }
    }
}

  

posted on 2022-12-31 16:32  宁静致远.  阅读(80)  评论(0编辑  收藏  举报