【学习笔记】Silverlight框架:Jounce(4)——事件通信
Prism、CM和Jounce里都有各自的事件通信機制,也都叫EventAggregator。
相比于Prism,Jounce里的EventAggregator的風格更接近CM。當然作者也是這么說的:The pattern here is based on the lightweight version Rob Eisenburg introduced with Caliburn Micro。
這里涉及的類主要有三個:兩個接口類IEventAggregator和IEventSink<in T>,還有實現IEventAggregator的EventAggregatorService。
IEventAggregator定義了四個方法,其中三個是訂閱消息、在UI線程上訂閱消息和取消訂閱,接受的參數都是IEventSink;最后一個方法是用來發布消息的。
EventAggregatorService內部維護了一個弱引用的字典用來存儲訂閱了消息的IEventSink,當在某個地方誰誰誰發布消息的時候,就會在這個字典里去找泛型類型匹配的IEventSink并調用其唯一的一個方法HandleEvent。
其實就是觀察者,你懂的。
來實例操作下,通過模板新建解決方案,整個結構如下:
MainPage分為左右2個部分,分別用來存放PublishIntSubscribeGuid和PublishGuidSubscribeInt。
PublishIntSubscribeGuid會發布Int值,然后接收Guid的消息。
PublishGuidSubscribeInt會發布Guid,然后接收Int值的消息。
兩個頁面都是上面一個按鈕,下面一個TextBox用來顯示收到的消息,后臺代碼也差不多,我們來看看其中一個:
[Export]public partial class PublishIntSubscribeGuid : UserControl, IEventSink<Guid>, IPartImportsSatisfiedNotification{[Import]public IEventAggregator EventAggregator { get; set; }public PublishIntSubscribeGuid(){InitializeComponent();this.PublishButton.Click += new RoutedEventHandler(PublishButton_Click);}void PublishButton_Click(object sender, RoutedEventArgs e){var random = new Random();this.EventAggregator.Publish(random.Next());}#region IPartImportsSatisfiedNotification 成員public void OnImportsSatisfied(){EventAggregator.SubscribeOnDispatcher(this);}#endregion#region IEventSink<Guid> 成員public void HandleEvent(Guid publishedEvent){this.OutTextBox.Text += "\r\n" + publishedEvent;}#endregion}
首先,要訂閱Guid類型的消息先要實現IEventSink接口,泛型類型是Guid。
然后,要實現IPartImportsSatisfiedNotification接口,在MEF導入IEventAggregator后,注冊完成消息訂閱(這里在UI線程上訂閱),這樣當有某個地方發布類型是GUID的消息時,HandleEvent(Guid publishedEvent)方法就會最終被調用。
另外,在點擊發布消息的按鈕時候發布個隨機的Int值,當某個地方訂閱了Int類型的消息時,那個地方就會接收到這個隨機值。
實際應用可能要復雜點,泛型會是某個實體類或者某種錯誤等等。
看一下效果:
代碼:這里
PS:
1.打開APP.CS,可以看到通過模板創建的解決方案默認使APP實現了 IEventSink<UnhandledExceptionEvent>接口,這個就是原來通過Application.Current.UnhandledException注冊的系統未處理錯誤,Jounce在ApplicationService里進行了注冊和轉換并通過事件系統進行了發布。這樣就可以在別的地方也進行偵聽。
2.整個事件通信系統是Jounce頁面加載和導航的基礎,可以實現IEventSink<ViewNavigationArgs>并偵聽下看看。
轉載于:https://www.cnblogs.com/HalfwayMonk/archive/2011/07/28/2120465.html
總結
以上是生活随笔為你收集整理的【学习笔记】Silverlight框架:Jounce(4)——事件通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生孩子花多少钱啊?
- 下一篇: asp.net mvc3 Razor引擎