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

相关推荐
金山几座1 天前
C#学习记录-类(Class)
开发语言·学习·c#
The Shio2 天前
OptiByte:一个可视化协议设计与多语言代码生成工具
网络·物联网·c#·.net·业界资讯
我是唐青枫2 天前
C#.NET Pipelines 深入解析:高性能 IO 管道与零拷贝协议处理实战
c#·.net
求学中--2 天前
万物互联的钥匙:HarmonyOS SDK 深度解析与实战指南
wpf
蓝天星空2 天前
跨平台开发语言对比
开发语言·c#·.net
阿蒙Amon2 天前
C#常用类库-详解JetBrains.Annotations
前端·数据库·c#
老鱼说AI2 天前
《深入理解计算机系统》(CSAPP)2.2:整数数据类型与底层机器级表示
开发语言·汇编·算法·c#
历程里程碑2 天前
40 UDP - 2 C++实现英汉词典查询服务
linux·开发语言·数据结构·c++·ide·c#·vim
阿蒙Amon2 天前
C#常用类库-详解Polly
开发语言·c#
唐青枫2 天前
C#.NET stackalloc 深入解析:栈上分配、Span 配合与使用边界
c#·.net