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

一、Commands

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

  1. public static class GlobalCommands  
  2. {  
  3. public static CompositeCommand MyCompositeCommand = new CompositeCommand();  
  4. }  
public static class GlobalCommands
{
public static CompositeCommand MyCompositeCommand = new CompositeCommand();
}

  1. GlobalCommands.MyCompositeCommand.RegisterCommand(command1);  
  2. GlobalCommands.MyCompositeCommand.RegisterCommand(command2);  
GlobalCommands.MyCompositeCommand.RegisterCommand(command1);
GlobalCommands.MyCompositeCommand.RegisterCommand(command2);

  1. <Button Name="MyCompositeCommandButton" Command="{x:Static  
  2. local:GlobalCommands.MyCompositeCommand}">Execute My Composite Command </Button>  
<Button Name="MyCompositeCommandButton" Command="{x:Static
local:GlobalCommands.MyCompositeCommand}">Execute My Composite Command </Button>

二、Shared Service

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

  1. protected void RegisterViewsAndServices()  
  2. {  
  3. _container.RegisterType<IMarketFeedService, MarketFeedService>(new  
  4. ContainerControlledLifetimeManager());  
  5. //...  
  6. }  
protected void RegisterViewsAndServices()
{
_container.RegisterType<IMarketFeedService, MarketFeedService>(new
ContainerControlledLifetimeManager());
//...
}

三、Event Aggregation

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

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

  1. public class TickerSymbolSelectedEvent : CompositePresentationEvent<string>{}  
public class TickerSymbolSelectedEvent : CompositePresentationEvent<string>{}
  1. this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");  
this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");

  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. }  
public void Run()
{
...
this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Subscribe(ShowNews,
ThreadOption.UIThread);
);
}
public void ShowNews(string companySymbol)
{
this.articlePresentationModel.SetTickerSymbol(companySymbol);
}

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

  1. FundAddedEvent fundAddedEvent = this.eventAggregator.GetEvent<FundAddedEvent>();  
  2. fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.UIThread, false,  
  3. fundOrder => fundOrder.CustomerId == this.customerId);  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值