原文:
[MVVM Light]Messenger 的使用當我們使用MVVM開發模式進行開發時,ViewModel之間的通信常常是很頭疼的事情,好在MVVM Light提供了Messenger類可以輕松的在ViewModel之間傳遞消息。
Messenger
Messenger 其他類成員可以通過Register 方法 來建立與Messenger的聯系,注冊時包含當收到Message的時候要執行的方法。當使用Send方法時,注冊的相關的方法将會被調用。
The Messager is a class allowing objects to exchange message.
主要成員:
Register method :
//Registers a recipient for a type of message TMessage. The action
//parameter will be executed when a corresponding message is sent.
void Register<TMessage>(object recipient, object token, Action<TMessage> action);
void Register<TMessage>(object recipient, Action<TMessage> action);
void Register<TMessage>(object recipient, object token, bool receiveDerivedMessagesToo, Action<TMessage> action);
void Register<TMessage>(object recipient, bool receiveDerivedMessagesToo, Action<TMessage> action);
Send method
例子:
在MainViewModel類中
Messenger.Default.Register<Brush>(this, true, m => BackgroundBrush = m);
表示注冊Brush類型的Message。
在SettingViewModel類中
Messenger.Default.Send<Brush, MainViewModel>(
GetCurrentBrush());
當執行這段代碼時,會調用MainViewModel 注冊message時所寫的m => BackgroundBrush = m;
其中 m 表示消息内容。
Register函數的結構如下: