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

相关推荐
冒泡P3 小时前
Unity Shader入门(更新中)
unity·c#·游戏引擎·图形渲染·着色器
冰茶_8 小时前
MAUI与XAML交互:构建跨平台应用的关键技巧
microsoft·微软·c#·交互·maui·xamarin
CodeCraft Studio10 小时前
PDF处理控件Aspose.PDF教程:以编程方式将PDF转换为Word
pdf·c#·word
Singe.Chen13 小时前
C#中Task.Run的线程管理最佳实践与并发控制
c#·.net·wpf
阿蒙Amon15 小时前
01. C#入门系列【你的第一个程序】从Hello World开始
开发语言·c#
上位机_0x17 小时前
c#中添加visionpro控件(联合编程)
开发语言·数码相机·c#
Dongwoo Jeong17 小时前
C# 初学者的 3 种重构模式
重构·c#·refactoring·immutable data
He BianGu18 小时前
演示:【WPF-WinCC3D】 3D工业组态监控平台源代码
wpf
拜特流动18 小时前
WPF核心类继承树结构
wpf
天天进步201518 小时前
C# Prism框架详解:构建模块化WPF应用程序
开发语言·c#·wpf