您的位置:首页 > 其它

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

2016-08-12 09:15 816 查看
一、Commands

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

[csharp]
view plain
copy

print?

public static class GlobalCommands  
{  
public static CompositeCommand MyCompositeCommand = new CompositeCommand();  
}  



public static class GlobalCommands
{
public static CompositeCommand MyCompositeCommand = new CompositeCommand();
}


[csharp]
view plain
copy

print?

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



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


[html]
view plain
copy

print?

<Button Name="MyCompositeCommandButton" Command="{x:Static  
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。

[csharp]
view plain
copy

print?

protected void RegisterViewsAndServices()  
{  
_container.RegisterType<IMarketFeedService, MarketFeedService>(new  
ContainerControlledLifetimeManager());  
//...  
}  



protected void RegisterViewsAndServices()
{
_container.RegisterType<IMarketFeedService, MarketFeedService>(new
ContainerControlledLifetimeManager());
//...
}


三、Event Aggregation

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

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

[csharp]
view plain
copy

print?

public class TickerSymbolSelectedEvent : CompositePresentationEvent<string>{}  



public class TickerSymbolSelectedEvent : CompositePresentationEvent<string>{}


[csharp]
view plain
copy

print?

this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");  



this.eventAggregator.GetEvent<TickerSymbolSelectedEvent>().Publish("STOCK0");


[csharp]
view plain
copy

print?

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



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


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

[csharp]
view plain
copy

print?

FundAddedEvent fundAddedEvent = this.eventAggregator.GetEvent<FundAddedEvent>();  
fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.UIThread, false,  
fundOrder => fundOrder.CustomerId == this.customerId);  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐