MVVMLight的Messenger

本文详细解析了MvvmLight框架中Messenger的注册方法及其工作原理。通过实例演示如何使用Messenger进行跨组件通信,包括如何注册消息接收者及发送消息。


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<str
ing> 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的源码,发现它也是使用这个方法来调用Action,

所以这个recipient应该是委托的方法所在的对象,就是使用放射调用方法的object参数

下面举个修改Mvvmlight的WelcomeTitle的例子,


我们可以在MainViewModel的构造函数里注册修改文字的委托

            Messenger.Default.Register<string>(this,"改文字", p => {
                this.WelcomeTitle = p;
            });

在界面上加一个Button,并在Click事件里SendMessage

            Messenger.Default.Send<string>("胜多负少", "改文字");


注意token要一样


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值