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

相关推荐
一然明月3 分钟前
C#语言基础详解和面向对象编程核心概念与高级特性详解(万字详解带示例代码)
开发语言·c#
flysh0515 分钟前
.NET 基础 - StringBuilder 类
开发语言·c#·编程语言·c#10
cjp5602 小时前
002.为C#动态链接库添加wpf窗体
microsoft·c#·wpf
齐鲁大虾2 小时前
如何通过C#调取打印机打印文本和图片
开发语言·c#
TDengine (老段)3 小时前
TDengine C# 语言连接器入门指南
大数据·数据库·c#·时序数据库·tdengine·涛思数据
凯新生物3 小时前
Mannose-PEG-CY5.5,CY5.5-PEG-Mannose技术手册:分子量选型与溶解性说明
javascript·c#·bash·symfony
hixiong1233 小时前
C# OpenVinoSharp部署Yolo26模型进行推理
开发语言·c#·openvino·yolo26
bugcome_com3 小时前
WPF控件模板
wpf
观无4 小时前
VisionPro的二维码识别
c#
Fairy要carry5 小时前
面试:LLM-分词
开发语言·c#