我正在尝试在 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/