轉載:http://www.cnblogs.com/tianciliangen/p/5013144.html
在開發大型復雜系統時,我們通常會按功能將系統分成很多模塊,這樣模塊就可以獨立的並行開發、測試、部署、修改。使用Prism框架設計表現層時,我們也會遵循這個原則,按功能相關性將界面划分為多個模塊,每個模塊又包含多個Region。這就需要解決模塊之間、Region之間經常需要進行通信的問題,Prism提供了以下幾種方式:
1、聚合事件(Event aggregation)
使用方式,先在一個公共模塊中定義一個事件MyEvent ,傳輸數據為MyEntity。
public class MyEvent : CompositePresentationEvent<MyEntity> { }
然后在需要等待處理事件的模塊中訂閱事件,如下所示:
private IEventAggregator eventAggregator;
eventAggregator = (IEventAggregator)ServiceLocator.Current.GetService(typeof(IEventAggregator));
eventAggregator.GetEvent<MyEvent>().Subscribe(MyEventHandler, true);
public void MyEventHandler(MyEntity myEntity) {
}
eventAggregator 相當於一個全局的集合,保存了所有訂閱的事件。
在發起通信的模塊中發布事件,如下所示:
eventAggregator.GetEvent<CreatePlanEvent>().Publish(new MyEntity());
2、全局命令
使用方式,在公共模塊中定義一個全局命令類:
public static class GlobalCommands {
public static CompositeCommand OpenCommand = new CompositeCommand();
}
在使用該命令的View中:
<Button Command="{x:Static s:GlobalCommands.OpenCommand }" >
在響應該命令的模塊中:
public ICommand OpenCommand { get; set; }
OpenCommand = new RelayCommand(param => this.Open(param));
GlobalCommands.OpenCommand.RegisterCommand(OpenCommand);
不用綁定時可以這樣執行:
GlobalCommands.OpenCommand.Execute(param);
3、Region context
在Prism安裝文件中自帶的UIComposition例子中演示了兩個Tab頁共享一個數據集,
用法是在View中:
prism:RegionManager.RegionContext="{Binding CurrentEmployee}"
在兩個Tab頁的View的后台代碼中:
RegionContext.GetObservableContext(this).PropertyChanged += (s, e) => employeeDetailsViewModel.CurrentEmployee = RegionContext.GetObservableContext(this).Value as Employee;
我們還可以利用Region.Context屬性共享數據,Region.Context中可以保存任何該Region需要與其他Region共享的數據。
因此我在實際使用時用Region.Context來保存一個控件對象的引用。如下所示:
在一個模塊中保存
mainRegion.Context = new ContentControl();
在另一個模塊中取出
IRegion mainRegion = regionManager.Regions["MainRegion"]; if (mainRegion == null) return; ContentControlpane = mainRegion.Context as ContentControl;
因為regionManager是全局的,所以可以隨時獲得感興趣的Region和Context
4、共享服務
這種方法我們在前面已經接觸到了,如:
eventAggregator = (IEventAggregator)ServiceLocator.Current.GetService(typeof(IEventAggregator));
還可以,container= (IEventAggregator)ServiceLocator.Current.GetService(typeof(IUnityContainer));
IEventAggregator和IUnityContainer是Prism已有的服務,我們還可以自定義服務,請參考Prism自帶的StockTrader RI例子
中的IMarketHistoryService服務。
