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

相关推荐
步步为营DotNet12 分钟前
NET 11 中 C# 14 新特性在云原生微服务架构的深度实践
云原生·架构·c#
不会编程的懒洋洋1 小时前
WPF 性能优化+异步+渲染
开发语言·笔记·性能优化·c#·wpf·图形渲染·线程
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ13 小时前
通过java后端代码来实现给word内容补充格式文本内容控件,以及 设置控件的标记和标题
java·c#·word
Hesionberger19 小时前
LeetCode79:单词搜索DFS回溯详解
java·开发语言·c++·python·算法·leetcode·c#
曹牧21 小时前
C#:同一项目中维护多个版本的代码
开发语言·c#
工程师00721 小时前
C# UI 跨线程刷新:Invoke/BeginInvoke 原理与封装
c#·invoke·begininvoke
码农刚子1 天前
.NET 8 Web开发入门(二):C# 现代语法速成——为 Web API 量身定制
c#·.net
求学中--1 天前
状态管理一文通:@State、@Prop、@Link、@Provide/Consume全解析
人工智能·小程序·uni-app·wpf·harmonyos
江沉晚呤时1 天前
用 C# 玩转 Scriban:自动生成报告、代码、文本,效率提升 10 倍
数据库·microsoft·c#·.net