xamarin - 如何以xamarin形式使用消息中心

标签 xamarin xamarin.forms

我正在尝试在 xamarin 表单中使用消息中心而不是 Messenger 我不知道消息中心我尝试使用以下代码在 xamarin 表单中订阅和发送消息

MessagingCenter.Send(this, "TodoTable", "Todo");

但是我不知道从哪里可以订阅此消息,我尝试了以下代码:

MessagingCenter.Subscribe<TodoClass>(this, Todo, async (sender, arg) =>
{
  await RefreshCommand.ExecuteAsync();
});

这给了我错误任何帮助将不胜感激:)

最佳答案

XF 消息中心的一个怪癖是(看起来)您需要知道谁将发送消息,以及可能谁将接收消息。

但是它可以是对象。订阅的签名是:

void MessagingCenter.Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender sender = null)

诀窍是这样订阅:

MessagingCenter.Subscribe<object>(this, "messageName", Action<object> callback)

这表示对象或从对象派生的任何东西都可以是发送者,即一切。

但是,如果您只想订阅特定类型实例发送的消息:

MessagingCenter.Subscribe<MyClass>(this, "messageName", Action<MyClass> callback)

使用完整签名有点可疑。基本上,它是说只有从源对象发送的订阅者在订阅时使用了该源对象。

  MessagingCenter.Subscribe<object, string>(this, "Hi", 
      (sender, arg) =>
      {
        DisplayAlert("Message Received", "arg=" + arg, "OK");
      },
      BindingContext);

如果您使用以下方式发送消息,上面的订阅者将不会收到该消息:

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

但是会收到以下内容

  MessagingCenter.Send<object, string>(BindingContext, "Hi", "John");

但是你为什么要给自己发送消息呢? (假设本例中订阅和发送位于同一页面)。

但是,如果多个页面具有完全相同的绑定(bind)上下文,则消息将发送给所有此类订阅者。例如,页面绑定(bind)到相同的 View 模型。

关于xamarin - 如何以xamarin形式使用消息中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41328977/

相关文章:

c# - 如何从 tabbarController.ViewControllerS 选定事件中删除/垃圾收集附加方法?

xamarin - 如何修复 Xamarin“找不到文件 xamarin.android.glide.disklrucache\4.12.0.4\buildTransitive\monoandroid10.0\..\..\jar\annotations.jar

ios - 续订Advance Apple中的免费配置文件

xaml - Xamarin.Forms 在运行时更改 UI 语言 (XAML)

Xamarin Google API 客户端不存在?

android - 将 Xamarin Forms View 呈现为 Android View 而不指定大小

visual-studio - Resource.Designer.cs 生成器在调试时缺少资源

ios - Apple IAP 收据验证返回代码 21002

xamarin - 如何以 Xamarin 形式解压缩下载的 Zip 文件

c# - 使用 content(body) 或多个参数的 restful API get 方法