下載app免費領取會員
MvvmLight里的Messenger的注冊方法有一個是這樣的:
//
// 摘要:
// Registers a recipient for a type of message TMessage. The action parameter will
// be executed when a corresponding message is sent.
// Registering a recipient does not create a hard reference to it, so if this recipient
// is deleted, no memory leak is caused.
//
// 參數:
// recipient:
// The recipient that will receive the messages.
//
// action:
// The action that will be executed when a message of type TMessage is sent.
//
// 類型參數:
// TMessage:
// The type of message that the recipient registers for.
void Register<TMessage>(object recipient, Action<TMessage> action);
這個TMessage是要傳送消息的類型,它就是action的參數,但是這個recipient有點費解。
這就要說到Action的使用問題
class Program
{
static void Main(string[] args)
{
Test test = new Test();
Action<string> action = new Action<string>(test.Excute);
action("ssdfsdf asdfsad");
MethodInfo minfo = action.Method;
minfo.Invoke(test, new object[] { "sdfsdf sdf"});
Console.ReadLine();
}
}
public class Test
{
public void Excute(string str)
{
Console.WriteLine(str);
}
}
重上面的小例子我可看出Action 也是可以使用反射來調用的,查看Messenger的源碼,發(fā)現它也是使用這個方法來調用Action,
所以這個recipient應該是委托的方法所在的對象,就是使用放射調用方法的object參數
下面舉個修改Mvvmlight的WelcomeTitle的例子,
我們可以在MainViewModel的構造函數里注冊修改文字的委托
Messenger.Default.Register<string>(this,"改文字", p => {
this.WelcomeTitle = p;
});
在界面上加一個Button,并在Click事件里SendMessage
Messenger.Default.Send<string>("勝多負少", "改文字");
注意token要一樣
本文版權歸腿腿教學網及原創(chuàng)作者所有,未經授權,謝絕轉載。
上一篇:二次開發(fā)教程:Revit開發(fā)區(qū)分基本墻,幕墻,疊層墻
下一篇:二次開發(fā)教程:C# 通過MVVMLight探索IOC
推薦專題