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 小时前
C#.NET ReadOnlySequence 深入解析:多段内存遍历与零拷贝协议解析
网络·c#·.net
人工智能AI技术3 小时前
GTC炸场!C#集成NemoClaw企业级Agent实战教程
人工智能·c#
金币闪耀3 小时前
一种winform实时刷新日志内容的方法
c#
Vae_Mars4 小时前
华睿MVP:C#脚本的应用一
笔记·c#
筱璦5 小时前
期货软件开发「启动加载页 / 初始化窗口」
前端·c#·策略模式·期货
qq_390760396 小时前
简单的线程安全日志记录器
开发语言·数据库·c#
醉酒柴柴6 小时前
word创建样式以后应用于所有新文件
开发语言·学习·c#·word
JosieBook7 小时前
【WinForm】C# WinForms 跨线程更新 UI 避坑指南
开发语言·ui·c#
阿蒙Amon8 小时前
C#常用类库-详解Playwright
开发语言·c#
JQLvopkk10 小时前
DeepSeek赋能新一代高智能化SCADA
人工智能·c#