stylet自带事件聚合器,使用事件聚合器可以让vm之间进行互相通信,在vm继承IHandle接口就行了,并且要在vm的构造函数中订阅消息。
简单说一下我要实现什么样的功能:在A_ViewModel中插入数据,点击“确定”按钮以后,
B_ViewModel对应的View层的DataGrid数据立马更新。
1.首先,创建一个事件类,例如DataUpdatedEvent
,以通知其他ViewModel数据已更新:
public class DataUpdatedEvent
{
// 通常不需要包含任何额外的属性或方法
}
2.在A_ViewModel
中,插入新数据时,发布DataUpdatedEvent
事件:
public class ProductServiceViewModel
{
private IEventAggregator _eventAggregator;
public ProductServiceViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
public void InsertData()
{
// 执行插入数据的操作
// 发布数据更新事件
_eventAggregator.PublishOnUIThread(new DataUpdatedEvent());
}
}
3.接下来,在B_ViewModel
中,订阅DataUpdatedEvent
事件,并在事件处理程序中更新DataGrid的数据源:
public class ProductViewModel : Screen, IHandle<DataUpdatedEvent>
{
private IEventAggregator _eventAggregator;
public ProductViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
public void Handle(DataUpdatedEvent message)
{
// 在这里处理数据更新事件,例如重新加载DataGrid的数据源
// 更新 DataGrid 数据源的代码
}
}
补充
private ObservableCollection<ProductInformation> _allUsers; // 将所有用户数据保存在一个属性中
public ObservableCollection<ProductInformation> AllUsers
{
get { return _allUsers; }
set
{
_allUsers = value;
NotifyOfPropertyChange(() => AllUsers);
}
}
private ObservableCollection<ProductInformation> _users;
public ObservableCollection<ProductInformation> Users
{
// 如果 FindName 不为空,返回 SearchResult,否则返回 AllUsers
get { return FindName != null ? SearchResult : AllUsers; }
private set
{
if (_users != value)
{
_users = value;
NotifyOfPropertyChange(nameof(Users)); // 通知界面刷新
}
}
}
了解:https://github.com/canton7/Stylet/wiki/The-EventAggregator