我正在尝试实现MessagingCenter来将数据从本机发送到pcl。在本机中,我设置了发送方法:
MessagingCenter.Send<Xamarin.Forms.Application>(App.Current, "Autorizzato");
下面是主页的代码:
protected override void OnStart()
{ MessagingCenter.Subscribe<Application>(this, "Autorizzato", (sender) => {
Debug.WriteLine("Ok!");
});
}代码正确执行,但没有触发MessagingCenter.Subscribe。实例类型都是相同的。
那么,如何解决这个问题呢?
发布于 2021-01-08 01:52:30
代码本身很好,但是您需要确保在发送消息时,TSender已经被实例化了,而不是null。
您在哪里调用MessagingCenter.Send?如果在MainActivity的OnCreate方法中调用它,请尝试将其移动到OnStart方法。
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnStart()
{
base.OnStart();
MessagingCenter.Send<Xamarin.Forms.Application>(App.Current, "Autorizzato");
}
{然后在App.cs中订阅
public partial class App : Application
{
public App()
{
InitializeComponent();
...
}
protected override void OnStart()
{
MessagingCenter.Subscribe<Application>(this, "Autorizzato", (sender) => {
Debug.WriteLine("Ok!");
});
}
}发布于 2021-01-07 13:04:01
如果你在这里查看我的博客:https://heartbeat.fritz.ai/xamarin-forms-messagingcenter-ab97eb923fd0
它提供了关于如何使用XF消息传递中心的详细信息。
如何订阅:
Subscribe<TSender> (object subscriber, string message, Action<TSender> callback, TSender source = null)因此,在应用程序中,它看起来类似于:
MessagingCenter.Subscribe<Sender> (this, "Hi", (sender) => {
// do something whenever the "Hi" message is sent
});你的发件人应该是这样的:
MessagingCenter.Send<MainPage> (this, "Hi");这些变化应该是好的,以使这项工作。
如有疑问,请随时回复
https://stackoverflow.com/questions/65612366
复制相似问题