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

相关推荐
mit6.8242 小时前
[C# starter-kit] 命令/查询职责分离CQRS | MediatR |
java·数据库·c#
beyond谚语4 小时前
C#学习小笔记(完整版)—— Patience
c#
爱吃小胖橘4 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎
IT小农工5 小时前
Word 为每一页设置不同页边距(VBA 宏)
开发语言·c#·word
sali-tec5 小时前
C# 基于halcon的视觉工作流-章42-手动识别文本
开发语言·人工智能·算法·计算机视觉·c#·ocr
咕白m6258 小时前
C# 合并多个PDF文档:高效解决方案
c#·.net
c#上位机9 小时前
wpf之MVVM中只读属性更新界面
c#·wpf·mvvm
就是有点傻9 小时前
WPF自定义控件之环形进度条
wpf
He BianGu9 小时前
【笔记】WPF中如何的动态设置DataGridTextColumn是否显示
笔记·wpf
技术支持者python,php12 小时前
winform本地上位机-ModbusRTC1.上位机控制台与数据监控(数据监控架构思维与图表系列)
c#