WPF自定义控件,聚合器模式传递消息

背景:自定义控件的消息传递和方法的调用可以使用聚合器来进行

定义聚合器:

cs 复制代码
public class EventAggregator
{
    public static ConcurrentDictionary<Type, List<Action<object>>> _handles = new ConcurrentDictionary<Type, List<Action<object>>>();

    // 订阅方法
    public void Register<T> (Action<object> action)
    {
        if (!_handles.ContainsKey(typeof (T)))
        {
            _handles[typeof (T)] = new List<Action<object>> ();
        }
        
        _handles[typeof(T)].Add(action);

        Debug.WriteLine(_handles[typeof(T)].Count);
    }

    // 给数据给调用的方法
    public void Send<T> (object obj)
    {
        if (_handles.ContainsKey(typeof(T)))
        {
            foreach (var actionin in _handles[typeof(T)])
            {
                actionin?.Invoke(obj);
            }
        }
    }

}

使用单例模式访问聚合器:

cs 复制代码
public class EventAggregatorRepository
{
    public EventAggregator eventAggregator;

    private static EventAggregatorRepository aggregatorRepository;
    private static object _lock = new object();

    public EventAggregatorRepository()
    {
        eventAggregator = new EventAggregator();
    }

    // 单例,只要一个事件聚合器
    public static EventAggregatorRepository GetInstance()
    {
        if (aggregatorRepository == null)
        {
            lock (_lock)
            {
                if (aggregatorRepository == null)
                {
                    aggregatorRepository = new EventAggregatorRepository();
                }
            }
        }
        return aggregatorRepository;
    }

}

在发送消息的控件中:

cs 复制代码
public SendMsgControlViewModel()
{
    SendMsgCommand = new RelayCommand<Student>(SendMsg);
}

private void SendMsg(object t)
{
    Student student = new Student()
    {
        Name = "梨花",
        Id = 12,
    };
    EventAggregatorRepository.GetInstance().eventAggregator.Send<Student>(student);
}

接收消息的控件中

cs 复制代码
public MainWindowViewModel()
{
	EventAggregatorRepository.GetInstance().eventAggregator.Register<Student>(ShowData);
}

private void ShowData(object obj)
{
	Student student = (Student)obj;
	Receive = student.Name;  // 需要显示的属性绑定

	MessageBox.Show(Receive);
}

相关:WPF中MVVM手动实现PropertyChanged和RelayCommand-CSDN博客

相关推荐
加号39 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
用户3952409988013 小时前
SqlSugar 连接 PostgreSQL 报错 42P01: relation does not exist 的排查与修复
c#
2601_9618752414 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
ServBay14 小时前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
2601_9618752419 小时前
法考备考计划表|学习计划|资料已整理
java·开发语言·学习·eclipse·tomcat·c#·hibernate
happyprince19 小时前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
Y学院20 小时前
C#游戏脚本开发全流程(Unity通用完整版)
游戏·unity·c#
淡海水21 小时前
38-Hybrid生态-LeanCLR总览
unity·架构·c#·热更新·clr·hybrid·leanclr
iCxhust1 天前
C# 生成命令行程序 将hex格式烧录程序转换成bin烧录格式
开发语言·汇编·单片机·嵌入式硬件·c#·微机原理
bugcome_com1 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf