簡體   English   中英

e。等待UWP中的異步對話框后無法設置取消

[英]e.Cancel cannot be set after awaiting async dialog in UWP

這適用於Windows 10 UWP應用。 當用戶嘗試離開頁面時,我希望讓用戶確認他是否要保存當前數據。

我已經覆蓋了OnNavigatingFrom ,如下所示。 但是,在異步MessageDialog之后,設置e.Cancel=false無效。 即使e.Cancel稍后設置為false,該頁面仍停留在當前頁面上。 請幫忙!

protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)

{
    e.Cancel = true; //if I don't put this at the top, the page navigates right away

    var yesCommand = new UICommand("Yes", async cmd => {

        try
        {
            await SaveWorkshetItem(false);
            e.Cancel = false;
        }
        catch (Exception ex)
        {
            await new MessageDialog("Error saving Worksheet Item. Please contact you administrator." + ex.Message + Environment.NewLine + ex.StackTrace).ShowAsync();
        }

    });

    var noCommand = new UICommand("No", cmd => { e.Cancel = false; });

    var cancelCommand = new UICommand("Cancel", cmd => { e.Cancel = true;  });

    var dialog = new MessageDialog("Do you want to save the current item before navigating away?");
    dialog.Options = MessageDialogOptions.None;
    dialog.Commands.Add(yesCommand);

    dialog.Commands.Add(noCommand);
    dialog.Commands.Add(cancelCommand);

    await dialog.ShowAsync();

    base.OnNavigatingFrom(e);

}

為了簡化此過程,即使我在示例MessageDialog之后改回e.Cancel=false ,以下代碼也使頁面永不離開。

protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)

{
    e.Cancel = true; //if I don't put this at the top, the page navigates right away

    await new MessageDialog("Do you want to save the current item before navigating away?").ShowAsync();

    e.Cancel = false;  //unconditionally setting this back to false and it still won't leave the page

    base.OnNavigatingFrom(e);
}

要自己處理導航,請設置Cancel = true(就像您已經做的那樣),然后調出對話框以獲取用戶輸入。 知道用戶的選擇后,如果用戶決定允許進行導航,則使用導航API(例如Frame.GoBack)執行所需的導航(基於e.NavigationMode)。

這是一些基本的示例代碼:

private bool isNavigationConfirmed = false;
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    base.OnNavigatingFrom(e);
    if (isNavigationConfirmed)
    {
        isNavigationConfirmed = false;
        return;
    }
    e.Cancel = true;

    var noCommand = new UICommand("No", cmd => { });
    var yesCommand = new UICommand("Yes", cmd =>
    {
        if (e.NavigationMode == NavigationMode.Back)
        {
            Frame.GoBack();
        }
        else
        {
            isNavigationConfirmed = true;
            Frame.Navigate(e.SourcePageType);
        }
    });

    var dialog = new MessageDialog("Do you want to allow navigation?");
    dialog.Options = MessageDialogOptions.None;
    dialog.Commands.Add(yesCommand);
    dialog.Commands.Add(noCommand);
    await dialog.ShowAsync();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM