WPF自定义控件,聚合器模式传递消息
•
移动开发
背景:自定义控件的消息传递和方法的调用可以使用聚合器来进行
定义聚合器:
public class EventAggregator
{
public static ConcurrentDictionary> _handles = new ConcurrentDictionary>();
// 订阅方法
public void Register (Action action)
{
if (!_handles.ContainsKey(typeof (T)))
{
_handles[typeof (T)] = new List> ();
}
_handles[typeof(T)].Add(action);
Debug.WriteLine(_handles[typeof(T)].Count);
}
// 给数据给调用的方法
public void Send (object obj)
{
if (_handles.ContainsKey(typeof(T)))
{
foreach (var actionin in _handles[typeof(T)])
{
actionin?.Invoke(obj);
}
}
}
}
使用单例模式访问聚合器:
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;
}
}
在发送消息的控件中:
public SendMsgControlViewModel()
{
SendMsgCommand = new RelayCommand(SendMsg);
}
private void SendMsg(object t)
{
Student student = new Student()
{
Name = "梨花",
Id = 12,
};
EventAggregatorRepository.GetInstance().eventAggregator.Send(student);
}
接收消息的控件中
public MainWindowViewModel()
{
EventAggregatorRepository.GetInstance().eventAggregator.Register(ShowData);
}
private void ShowData(object obj)
{
Student student = (Student)obj;
Receive = student.Name; // 需要显示的属性绑定
MessageBox.Show(Receive);
}
相关:WPF中MVVM手动实现PropertyChanged和RelayCommand-CSDN博客
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/2a1cda2f80.html
