MVVM Toolkit Messenger Useage

开发环境:VS2022社区版     

使用项目:WINUI 相关项目

 

下述为CommonMessage:

 1     public class CommonMessage<T1, T2, T3>
 2     {
 3 
 4         public string message;
 5         public T1 param1;
 6         public T2 param2;
 7         public T3 param3;
 8         public CommonMessage(string msg, T1 p1 = default, T2 p2 = default, T3 p3 = default)
 9         {
10             message = msg;
11             param1 = p1;
12             param2 = p2;
13             param3 = p3;
14         }
15     }

 

继承CommonMessage,按需要改写自己的Message类:

 1     //传输给UI界面层的消息
 2     public class ToUIMessage:CommonMessage<string, string,string>
 3     {
 4         public ToUIMessage(string msg, string p1 = default, string p2 = default, string p3 = default) : base(msg, p1, p2, p3)
 5         {
 6             // 在这里添加自己的构造函数的实现代码
 7         }
 8         public static void SendMessage(string title, string msg)
 9         {
10             WeakReferenceMessenger.Default.Send(new ToUIMessage(title, msg));
11         }
12     }

 

调用ToUIMessage发送信息的class中的SendMessage:

        private static void SendMessage(string title, string msg)
        {
            WeakReferenceMessenger.Default.Send(new ToUIMessage(title, msg));
        }

 

接收信息的class中进行相应的注册,即可接收发送信息类发出的相应Message:

            // Register the receiver in a module
            WeakReferenceMessenger.Default.Register<ToUIMessage>(this, (t,m)=>
            {
                App.ShowNotification(m.message, m.param1);
            });

 

接收信息涉及到的ShowNotification function写在App.xaml中以方便使用,当然这可以放于UI层的工具类中,代码如下:

        public static void ShowNotification(string title, string msg)
        {

            var builder = new AppNotificationBuilder()
                        .AddText($"{msg}.").SetTag(title);
            var notificationManager = AppNotificationManager.Default;
            notificationManager.Register();
            notificationManager.Show(builder.BuildNotification());
            notificationManager.Unregister();
        }

注意:

notificationManager注册后需要取消,否则下次调用时会因重复注册而报错。

 

参考链接Messenger - .NET Community Toolkit | Microsoft Learn

 

posted @ 2023-06-09 16:59  盛沧海  阅读(205)  评论(0编辑  收藏  举报