C# 是否在OnBackButtonPressed中等待任务并使用其结果返回方法?

C# 是否在OnBackButtonPressed中等待任务并使用其结果返回方法?,c#,xamarin.forms,async-await,C#,Xamarin.forms,Async Await,如果在屏幕上有任何更改(例如设置屏幕),我试图在离开屏幕时向用户显示一个对话框。然而DisplayAlert方法需要等待以获得我需要在OnBackButtonPressed中用作返回值的结果。我需要等待对话框的结果,然后执行OnBackButtonPressed方法的其余部分 我试图最终执行的代码应该与下面的代码类似: public partial class MainPage : ContentPage { private TestViewModel _vm; public

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

  • 在覆盖时,始终返回
    true
  • 在得到肯定回答后,调用
    base.onbackbutton按下
  • 这样:

    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,则对话框必须显示在BackButton Pressed:)上,因此代码中的
    条件不应该是属性,而是具有该逻辑的方法,对吗?我更改了问题的内容。希望现在它更有意义:)所以从重复问题中接受的答案不起作用?不,在我的情况下它不起作用,因为我需要返回对话框的结果