下載app免費領(lǐng)取會員
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.
//
// 參數(shù):
// recipient:
// The recipient that will receive the messages.
//
// action:
// The action that will be executed when a message of type TMessage is sent.
//
// 類型參數(shù):
// TMessage:
// The type of message that the recipient registers for.
void Register<TMessage>(object recipient, Action<TMessage> action);
這個TMessage是要傳送消息的類型,它就是action的參數(shù),但是這個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 也是可以使用反射來調(diào)用的,查看Messenger的源碼,發(fā)現(xiàn)它也是使用這個方法來調(diào)用Action,
所以這個recipient應(yīng)該是委托的方法所在的對象,就是使用放射調(diào)用方法的object參數(shù)
下面舉個修改Mvvmlight的WelcomeTitle的例子,
我們可以在MainViewModel的構(gòu)造函數(shù)里注冊修改文字的委托
Messenger.Default.Register<string>(this,"改文字", p => {
this.WelcomeTitle = p;
});
在界面上加一個Button,并在Click事件里SendMessage
Messenger.Default.Send<string>("勝多負(fù)少", "改文字");
注意token要一樣
本文版權(quán)歸腿腿教學(xué)網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。
上一篇:二次開發(fā)教程:Revit開發(fā)區(qū)分基本墻,幕墻,疊層墻
下一篇:二次開發(fā)教程:C# 通過MVVMLight探索IOC
推薦專題