Prism的IEventAggregator事件聚合器, 事件订阅发布, ViewModel之间的通讯

WPF中时常会遇到ViewModel之间的通讯,ViewModel并不知道自己的View,但是一个View发生的更改需要通知另外一个View。

举一个例子,软件界面上有个人信息,打开一个界面更改用户的信息后,这时显示个人信息的地方理应发生变化。此场景下更改用户后应该通知另一个显示用户信息的区域去更新。一般在设计时,我们会设计成一个个的用户控件,用户控件的数据来源于ViewModel,所以此时需要ViewModel之间通讯。

介绍场景后,我们利用Prism的IEventAggregator事件聚合器来实现。

步骤:
1.自定义事件

/// <summary>
/// 自定义事件——用户信息更改事件
/// </summary>
public class UserChangedEvent : CompositePresentationEvent<User> {
}

  

  1.  

2.订阅事件,结合上述场景应该在显示个人信息的地方订阅

IEventAggregator eventAggregator;
SubscriptionToken token;

/// <summary>
/// 构造方法
/// </summary>
public RightContainerViewModel() {
	//设计时状态判断
	if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") { 
		return; 
	}

	//获取事件聚合器
	eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
	//订阅事件
	token=eventAggregator.GetEvent<UserChangedEvent>().Subscribe(UserChanged); //提供UserChanged方法 

}

//事件触发
public void UserChanged(User user) {
	CurrentUser = user;
	if (token != null) {
		//取消订阅事件
		eventAggregator.GetEvent<UserChangedEvent>().Unsubscribe(UserChanged);
	}
}

  


3.发布事件,结合上述场景应该在更新用户信息的地方

private IEventAggregator eventAggregator;
/// <summary>
/// 构造方法
/// </summary>
public LeftContainerViewModel() {
	//设计时状态判断
	if (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv") {
		return;
	}
	//获取事件聚合器
	this.eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
}

/// <summary>
/// 按钮命令
/// </summary>
public ICommand UpdateCommand {
	get {
		return new DelegateCommand(() => {
			//发布事件
			eventAggregator.GetEvent<UserChangedEvent>().Publish(CurrentUser);   //提供UserChanged方法的参数CurrentUser
}); } }

  

 
下载地址:http://download.csdn.net/source/3474638
原文地址:https://www.cnblogs.com/cw_volcano/p/3613473.html