【问题标题】:Await a task in OnBackButtonPressed and use its result to return in the method? [duplicate]在 OnBackButtonPressed 中等待任务并使用其结果在方法中返回? [复制]
【发布时间】:2018-03-15 06:05:49
【问题描述】:

如果屏幕(例如设置屏幕)有任何更改,我会在离开屏幕时尝试向用户显示一个对话框。然而。 DisplayAlert 方法需要等待才能获得我需要用作 OnBackButtonPressed 中的返回值的结果。我需要等待对话框的结果,然后执行 OnBackButtonPressed 方法的其余部分。

我试图最终执行的代码应该类似于下面的代码:

public partial class MainPage : ContentPage
{
    private TestViewModel _vm;

    public MainPage()
    {
        InitializeComponent();
        _vm = new TestViewModel();
        BindingContext = _vm;
    }

    protected override bool OnBackButtonPressed()
    {
        if (_vm.IsUnchanged) return base.OnBackButtonPressed();

        var result = await DisplayAlert("Title", "Are you sure you want to leave the screen with unsave changes?", "Yes", "No");

        // returning false will exit the screen
        return !result;
    }
}

public class TestViewModel
{
    // this condition logic will evaluate if the user has made any changes to this screen and not saved them by pressing a "Save" button

    public bool IsUnchanged{ get; set; }

    public TestViewModel()
    {
    }
}

【问题讨论】:

  • 所以从重复问题接受的答案不起作用?
  • 不,在我的情况下它不起作用,因为我需要返回对话的结果

标签: c# xamarin.forms async-await


【解决方案1】:

试试这个:

  1. 在覆盖时,始终返回 true
  2. 在得到肯定回答后拨打base.OnBackButtonPressed

这边:

protected override bool OnBackButtonPressed()
{
    if (_vm.Condition) return base.OnBackButtonPressed();

    DisplayAlert("Title", "Are you sure you want to leave the screen?", "Yes", "No")
        .ContinueWith(answer => 
        {
            if(answer.Result)
                base.OnBackButtonPressed(); // I'm not sure, but maybe you should wrap it on a 'BeginInvokeOnMainThread'
        });

    return true;
}

【讨论】:

  • 感谢您的回答,但没有奏效。执行继续,并且该方法在显示警报对话框之前返回“true”。这里需要什么等待执行逻辑,直到对话框有响应
  • 对不起,我听不懂你的意思。这就是这段代码的目标:忽略“BackButtonPressed”事件并等待用户确认。方法覆盖确实会结束其执行。您的代码中必须执行的“逻辑”在哪里?
  • 没关系。我可能没有很好地解释它。无论如何,这个“逻辑”没有在这个测试项目中实现,但最终会检查用户是否对屏幕上显示的数据进行了任何更改。如果为 true,则必须显示对话框 OnBackButtonPressed :)
  • 所以你代码中的Condition不应该是一个属性,而是一个具有这种逻辑的方法,对吗?
  • 我更改了问题的内容。希望现在它更有意义:)
猜你喜欢
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 2013-08-06
  • 2016-06-15
  • 2019-06-22
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多