完善主体资料,免费赠送VIP会员!
* 主体类型
* 企业名称
* 信用代码
* 所在行业
* 企业规模
* 所在职位
* 姓名
* 所在行业
* 学历
* 工作性质
请先选择行业
您还可以选择以下福利:
行业福利,领完即止!

下载app免费领取会员

NULL

5cdd2dc095060.jpg

二次开发教程:MVVMLight的Messenger

发布于:2019-07-25 15:19:23

网友投稿

更多

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


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


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




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


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

                this.WelcomeTitle = p;

            });


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


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




注意token要一样

本文版权归腿腿教学网及原创作者所有,未经授权,谢绝转载。

未标题-1.jpg

上一篇:二次开发教程:Revit开发区分基本墙,幕墙,叠层墙

下一篇:二次开发教程:C# 通过MVVMLight探索IOC

60acb4e0ef112.png