Xamarin-MessagingCenter

Xamarin每天一篇,坚持一下。
可访问官方指南官方指南

Xamarin.Forms包括一个简单的消息传递服务来发送和接收消息。

消息中心的工作原理

有两个部分MessagingCenter:

  1. 订阅 - 收听具有特定签名的邮件,并在收到邮件时执行一些操作。多用户可以听同样的信息。
  2. 发送 - 发布消息让听众采取行动。如果没有监听者订阅,则该消息被忽略。
    该MessagingService是一个静态类Subscribe和Send方法是在整个解决方案中使用。

消息具有message用作消息地址的字符串参数。该Subscribe和Send方法使用泛型参数来进一步控制消息是如何传递-两条消息具有相同message的文字,但不同泛型类型参数将不会传递到同一用户。

这个API MessagingCenter很简单:

1.Subscribe<TSender> (object subscriber, string message,        
  Action<TSender> callback, TSender source = null)
2.Subscribe<TSender, TArgs> (object subscriber, string   
  message, Action<TSender, TArgs> callback, TSender          
  source = null)
3.Send<TSender> (TSender sender, string message)
4.Send<TSender, TArgs> (TSender sender, string message, TArgs args)         
5.Unsubscribe<TSender, TArgs> (object subscriber, string message)
6.Unsubscribe<TSender> (object subscriber, string   message)

这些方法在下面解释。

使用MessagingCenter

消息可能因用户交互(如按钮点击),系统事件(如控件更改状态)或其他事件(如异步下载完成)而发送。用户可能正在监听,以改变用户界面的外观,保存数据或触发其他操作。

简单的字符串消息

最简单的消息只包含message参数中的一个字符串。用Subscribe那方法侦听下面示出了用于一个简单的字符串信息-通知所述类型指定发送者预期为类型MainPage。解决方案中的任何类都可以使用以下语法订阅消息:

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});

在这个MainPage类中,下面的代码发送消息。该this参数是一个实例MainPage。

MessagingCenter.Send<MainPage> (this, "Hi");

该字符串不会更改 - 它指示消息类型并用于确定要通知的订阅者。这种消息用于指示发生了某些事件,例如“上传完成”,其中不需要进一步的信息。

传递一个参数

要传递消息的参数,请在Subscribe通用参数和动作签名中指定参数类型。

MessagingCenter.Subscribe<MainPage, string> (this, "Hi", (sender, arg) => {
    // do something whenever the "Hi" message is sent
    // using the 'arg' parameter which is a string
});

要使用参数发送消息,请在Send方法调用中包含Type泛型参数和参数值。

MessagingCenter.Send<MainPage, string> (this, "Hi", "John");

这个简单的例子使用了一个string参数,但是任何C#对象都可以被传递。

退订

一个对象可以取消订阅消息签名,这样就不会传递未来的消息。该Unsubscribe方法的语法应反映消息的签名(因此可能需要包括用于该消息参数中的通用类型的参数)。

MessagingCenter.Unsubscribe<MainPage> (this, "Hi");
MessagingCenter.Unsubscribe<MainPage, string> (this, "Hi");

欢迎评论!继续学习!

猜你喜欢

转载自blog.csdn.net/weixin_40132006/article/details/78736280