【问题标题】:Xamarin forms DisplayAlert not AwaitingXamarin 形成 DisplayAlert 不等待
【发布时间】:2020-05-19 08:02:42
【问题描述】:

我有一个事件会在按下 Android 硬件后退按钮时触发。这是它在 AppShell 类中的实现方式:

public event EventHandler<CancelEventArgs> BackButtonPressed;

protected override bool OnBackButtonPressed()
{
    var cancelArgs = new CancelEventArgs();
    BackButtonPressed?.Invoke(this, cancelArgs);
    return (cancelArgs.Cancel) ? true : base.OnBackButtonPressed();
}

在其他地方,我在视图模型中订阅了此事件。代码如下:

private async void _AppShell_BackButtonPressed(object sender, CancelEventArgs e)
{
     if (!await App.Current.MainPage.DisplayAlert(
          "My App",
          "Are you sure you want to cancel, you have unsaved changes",
          "ok",
          "cancel"))
          {
               e.Cancel = true;
          }
}

在 DisplayAlert 之前还发生了一些其他事情,但为简单起见,我已将其全部删除。

问题在于,当调用 DisplayAlert 时,执行返回到 OnBackButtonPressed,因此未相应设置取消参数。因此,DisplayAlert 似乎没有等待用户响应。这个问题怎么解决?

抱歉,如果我不清楚,我可以提供进一步的澄清.. 只是问:)

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: xamarin.forms async-await


    【解决方案1】:

    按照设计,我的解决方案是不可行的。答案是始终取消 OnBackButtonPressed() 方法并引发 MessagingCenter 事件,如下所示:

    protected override bool OnBackButtonPressed()
    {
         MessagingCenter.Send(this, "ANDROID_HARDWARE_BACK_BUTTON_TAPPED");
         return true;
    }
    

    那么当你处理事件调用时:

    await Shell.Current.Navigation.PopAsync(true);
    

    代替:

    await Shell.Current.SendBackButtonPressed
    

    由此我确定最佳做法是始终使用 PopAsync 而不是 SendBackButtonPressed 来避免不必要的递归。

    【讨论】:

      【解决方案2】:

      通过覆盖OnAppearing() 方法来使用显示警报怎么样?

      protected async override void OnAppearing() {
        var result = await App.Current.MainPage.DisplayAlert(
          "My App",
          "Are you sure you want to cancel, you have unsaved changes",
          "ok",
          "cancel"
        )
        base.OnAppearing();
        if (!result)
        {
          e.Cancel = true;
        }
      }
      

      【讨论】:

      • 嗨 Nicapuchino,当用户通过点击 Android 硬件后退按钮从相关页面导航返回时,我试图捕捉未保存的更改。抱歉,也许我不清楚,但我不确定我是否完全理解你的建议。你是在建议我截取后续页面中未保存的更改吗?
      • 抱歉,如果我误解了您的问题,但我的意思是覆盖 OnAppearing(如果您想在页面即将出现时等待 DisplayAlert)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多