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

相关推荐
心本无晴.2 小时前
RAG技术详解:从原理到实战应用
开发语言·c#
月巴月巴白勺合鸟月半3 小时前
用AI生成一个简单的视频剪辑工具 的后续 的后续
c#
flysh053 小时前
C# 核心进阶:深度解析继承(Inheritance)与多态机制
开发语言·c#
小码编匠3 小时前
C# 串口通信不再踩坑:一次发送、分包接收的零丢失实战秘籍
后端·c#·.net
lingxiao168883 小时前
vs脚本自动复制生成的文件至指定的位置
c#·脚本
kylezhao20193 小时前
第二节、C# 上位机核心数据类型详解(工控场景实战版)
开发语言·c#·上位机
kylezhao20193 小时前
C# 数组核心全面详解
c#·数组
bugcome_com5 小时前
WPF 中控件样式定义的三种方式详解
wpf
唐青枫5 小时前
深入理解 Interlocked.CompareExchange:C#.NET 原子操作核心原理
c#·.net
Psycho_MrZhang15 小时前
Ray 设计思想总结
wpf