Prism应用开发(八)——松耦合组件之间通信

来源:互联网 发布:人工智能电影观后感 编辑:程序博客网 时间:2024/06/09 02:34

一、Commands

创建一个全局的command,该command将会在各个组件之间共享。

[csharp] view plain copy
print?
  1. public static class GlobalCommands  
  2. {  
  3. public static CompositeCommand MyCompositeCommand = new CompositeCommand();  
  4. }  

[csharp] view plain copy
print?
  1. GlobalCommands.MyCompositeCommand.RegisterCommand(command1);  
  2. GlobalCommands.MyCompositeCommand.RegisterCommand(command2);  

[html] view plain copy
print?
  1. <Button Name="MyCompositeCommandButton" Command="{x:Static  
  2. local:GlobalCommands.MyCompositeCommand}">Execute My Composite Command </Button>  

二、Shared Service

module之间可以通过Shared Service相互通信而不用直接引用另一个module。

[csharp] view plain copy
print?
  1. protected void RegisterViewsAndServices()  
  2. {  
  3. _container.RegisterType<IMarketFeedService, MarketFeedService>(new  
  4. ContainerControlledLifetimeManager());  
  5. //...  
  6. }  

三、Event Aggregation

Prism提供了为松耦合组件之间通信提供了事件的机制。这个机制基于event aggregator service。允许发布和订阅事件而不用使得各个module引用对方。

下面的代码用户创建,发布和订阅事件

[csharp] view plain copy
print?
  1. public class TickerSymbolSelectedEvent : CompositePresentationEvent<string>{}  
[csharp] view plain copy
print?
  1. this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");  

[csharp] view plain copy
print?
  1. public void Run()  
  2. {  
  3. ...  
  4. this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Subscribe(ShowNews,  
  5. ThreadOption.UIThread);  
  6. );  
  7. }  
  8. public void ShowNews(string companySymbol)  
  9. {  
  10. this.articlePresentationModel.SetTickerSymbol(companySymbol);  
  11. }  

subscribe还提供了用于过滤的参数,例如:

[csharp] view plain copy
print?
  1. FundAddedEvent fundAddedEvent = this.eventAggregator.GetEvent<FundAddedEvent>();  
  2. fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.UIThread, false,  
  3. fundOrder => fundOrder.CustomerId == this.customerId);  

0 0
原创粉丝点击