如果用户按xamarin形式的硬件后退按钮,如何退订MessagingCenter?

时间:2018-12-17 08:11:45

标签: xamarin xamarin.forms

在我的按钮单击事件中,我订阅了消息传递中心

    bool isDataReceived = false;
    MessagingCenter.Subscribe<Dimention>(this, "Print", (sender) =>
                                    {
                                        isDataReceived = true;
                                        PopulateData(sender);
                                        if (isDataReceived)
                                        {
                                            MessagingCenter.Unsubscribe<Dimention>(this, "Print");
                                        }
                                    });

我正在从弹出窗口发送数据

MessagingCenter.Send<Dimention>(data, "Print");

但是,当用户按下硬件后退按钮而不发送值时,如何取消订阅消息中心。

2 个答案:

答案 0 :(得分:2)

您可以覆盖BackButton事件

 protected override bool OnBackButtonPressed()
        {    

              base.OnBackButtonPressed();

              MessagingCenter.Unsubscribe<Dimention>(this, "Print");    
              return false;    

        }

答案 1 :(得分:0)

您还可以通过将代码添加到OnDisappearing方法来确保您正在退订消息传递中心:

protected override void OnDisappearing()
{
    base.OnDisappearing();
    MessagingCenter.Unsubscribe<Dimention>(this, "Print");
}