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

相关推荐
拾荒的小海螺19 分钟前
C#:PdfiumViewer 高效解析和操作 PDF 的技术指南
开发语言·pdf·c#
缺点内向37 分钟前
C#: 精准掌控Excel工作流——激活工作表与选择单元格实战
开发语言·c#·excel
fireworkseasycold42 分钟前
wpf 基于 JSON 的扩展配置 (Extended Config)” 功能
oracle·json·wpf
一刻钟.1 小时前
DataGridView和定时器
开发语言·c#
咕白m6251 小时前
通过 C# 拆分 Excel 工作表
后端·c#
Bruce_Cheung2 小时前
UOS环境C#/Avalonia将文件剪切到剪切(粘贴)板实现
c#·avalonia
kylezhao20195 小时前
C#上位机实现权限管理
开发语言·c#
工藤新一OL6 小时前
如何做COM组件
c#·visual studio
刘97536 小时前
【第23天】23c#今日小结
开发语言·c#
xiaowu0806 小时前
C# 把dll分别放在指定的文件夹的方法
开发语言·c#