Prism應用開發(八)——松耦合組件之間通信

一、Commands

創建一個全局的command,該command將會在各個組件之間共享。

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

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

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

二、Shared Service

module之間可以通過Shared Service相互通信而不用直接引用另一個module。

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

三、Event Aggregation

Prism提供了爲松耦合組件之間通信提供了事件的機制。這個機制基於event aggregator service。允許發佈和訂閱事件而不用使得各個module引用對方。

下面的代碼用戶創建,發佈和訂閱事件

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

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

subscribe還提供了用於過濾的參數,例如:

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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章