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

相关推荐
qq_392397129 小时前
Redis常用操作
数据库·redis·wpf
三千道应用题12 小时前
WPF学习笔记(25)MVVM框架与项目实例
wpf
江山如画,佳人北望12 小时前
C#程序入门
开发语言·windows·c#
与火星的孩子对话13 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
future141213 小时前
C#每日学习日记
java·学习·c#
军训猫猫头17 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
厦门德仔19 小时前
【WPF】WPF(样式)
android·java·wpf
葬歌倾城1 天前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue1 天前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王1 天前
hello判断
开发语言·c#