MVVMLight的Messenger

来源:互联网 发布:revit软件 编辑:程序博客网 时间:2024/05/22 13:56


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要一样


0 0
原创粉丝点击