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

    }
}

posted @ 2023-10-26 11:04  窦戈  阅读(262)  评论(0编辑  收藏  举报