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 小时前
第二章:深入 Unity 资源导入管线 (Asset Import Pipeline)
游戏·unity·c#·游戏引擎·游戏程序
WPF工业上位机2 小时前
匠心研智造,同心赴新程-WPF硬件通讯之串口&Socket
wpf
爱炸薯条的小朋友3 小时前
全局锁的性能优势,以及链路优化为何常常低于预期——基于 `MatPoolsTest` 中小图池与大图池的实战复盘
opencv·算法·c#
心蓝无敌5 小时前
攻克Avalonia Dock布局中WebView等原生控件无法停靠的难题
c#·visual studio·avalonia·avalonia dock
guygg886 小时前
C# 监听数据库数据变化(SqlDependency 实现)
数据库·oracle·c#
爱炸薯条的小朋友9 小时前
C#由窗体原子表溢出造成的软件闪退,根本原因补充
开发语言·c#·wpf
我是苏苏10 小时前
C#基础:Winform桌面开发中自定义组件UI、属性及事件
服务器·数据库·c#
2401_8530878810 小时前
Confluence 替代落地复盘:存量数据迁移、权限重构、信创适配踩坑总结
开发语言·重构·c#
曹牧11 小时前
C#:DataGridView控件中展示JSON内容
开发语言·c#·json
He少年11 小时前
【AI路径代理与业务接入 — 成功失败感悟】
人工智能·c#