等待OnBackButtonPressed中的任务并使用其结果返回方法?

时间:2018-03-14 19:39:36

标签: c# xamarin.forms async-await

如果屏幕上有任何更改(例如“设置”屏幕),我试图在离开屏幕时向用户显示一个对话框。然而。 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()
    {
    }
}

2 个答案:

答案 0 :(得分:-1)

试试这个:

  1. 在您的覆盖上,始终返回true;
  2. 在肯定答复后致电base.OnBackButtonPressed
  3. 这样:

    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;
    }
    

答案 1 :(得分:-3)

要使用await关键字,您的方法必须为async

    protected override async Task<bool> OnBackButtonPressed()
    {
        if (_vm.Condition) return await base.OnBackButtonPressed();

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

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

否则,您可以将DisplayAlert的结果分配给Task并致电Wait

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

        var task = DisplayAlert("Title", "Are you sure you want to leave the screen?", "Yes", "No");
        task.Wait();
        // returning false will exit the screen
        return !task.Result;
    }