Xamarin 表单 MessagingCenter 取消订阅未按预期工作

标签 xamarin xamarin.android xamarin.forms

当我在应用程序中多次导航时,MessagingCenter.Subscribe() 内编写的功能会被多次调用。但每次订阅之前,我都会在构造函数中取消订阅,如下所示,但仍然不起作用。

MessagingCenter.Unsubscribe<SubmitPage>(this,"Save");
MessagingCenter.Subscribe<SubmitPage>(this, "Save", (sender) =>
{
   DisplayToastOnSuccessfulSubmission();
});

在我的应用程序中,我有 6 个页面( git ),我使用 MessagingCenter.Send 将数据保存在第 6 页中,并且将在第 2 页中订阅相同的数据,并且保存的消息将显示在第 2 页中(导航到该页面后) )。

现在我像 2->1->2->3->4->5->6 一样导航,在这种特殊情况下 DisplayToastOnSuccessfulSubmission() 将被调用两次(因为 Page2 构造函数被调用两次)。

我什至尝试将相同的代码放入 OnAppearing 中。 我无法在 OnDisappear 中取消订阅,因为我需要在到达第 6 页进行保存时连接事件。

在示例项目中重现了相同的行为并在此处添加了 https://github.com/suchithm/MessageCenterSampleApp
Drop box link

执行此操作的正确方法是什么?

最佳答案

But each time before subscribing, I do unsubscribe to the same in constructor as follows, still it didn't worked.

MessagingCenter.Subscribe() 被多次调用,因为代码中有两个 Page2 实例,它们都使用 MessagingCenter.Subscribe() 方法,这就是 Unsubscribe 不起作用的原因。

您可以将 page2() 修改为单例,以确保您的项目中只有一个 Page2 实例,之后当你发送一条消息, MessagingCenter.Subscribe() 仅调用一次。

Page2.cs:

public static Page2 instance = new Page2();

public static Page2 GetPage2Instance()
{
    if(instance == null)
    {
        return new Page2();
    }
    return instance;
}

private Page2()
{
    InitializeComponent();
    MessagingCenter.Unsubscribe<Page2>(this, "SaveToastPage2");
    MessagingCenter.Subscribe<Page2>(this, "SaveToastPage2", (sender) =>
    {
       DisplayToastOnSuccessfulSubmission();
    }
 }

当您发送消息时:

MessagingCenter.Send(Page2.GetPage2Instance(), "SaveToastPage2");

编辑:

请记住,将 Page2 类的构造函数声明为私有(private),以确保您的项目中只有一个 Page2 实例。

private Page2()
{
   ...
}

修改您的Page1.cs代码:

async void Handle_Next(object sender, System.EventArgs e)
{
    await App.NavigationRef.PushAsync(Page2.GetPage2Instance(), true);
}

关于Xamarin 表单 MessagingCenter 取消订阅未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44720764/

相关文章:

c# - 字符串填充不占用相同的字符间距

listview - 缓存图像 (ffimageloading) 在 android 上出现 OUT OF MEMORY 错误 - xamarin 表单

android - Monodroid - 如何调试 android 小部件

android - 导航到其他页面时如何阻止按钮双击

c# - 应用程序关闭时的 Xamarin.Forms iOS PushNotification

android - Xamarin Forms IsVisible 属性与动画

c# - 当我们在 Xamarin.Forms Android 应用程序中将目标 API 版本更改为 26 时无法读取/写入文件

c# - 使用 C# 与 NSUrlSession 的 HTTP POST 多部分表单数据

c# - 如何避免导航堆栈上已存在打开的页面?

button - Xamarin.Forms XAML 圆形按钮