在等待UWP中的异步对话后,无法设置e.Cancel

时间:2018-03-09 22:03:22

标签: c# uwp windows-store-apps windows-10-universal uwp-xaml

这适用于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);

}

为了简化此操作,以下代码会导致页面永远不会离开,即使我在样本e.Cancel=false之后更改MessageDialog

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

1 个答案:

答案 0 :(得分:3)

要自己处理导航,请设置Cancel = true(如您所做),然后调出对话框以获取用户输入。一旦您了解了用户的选择,如果用户决定允许导航发生,请使用导航API(例如Frame.GoBack)执行所需的导航(基于e.NavigationMode)。

以下是一些基本的示例代码:

<select id="my-select"></select>
<script>
    let people = [{
            id: 1,
            fullname: 'David Lebee'
        },
        {
            id: 2,
            fullname: 'Chuck Norris'
        },
    ];

    function confirmAsync(success, fail) {
        setTimeout(() => {
            if (confirm('are you sure')) {
                success();
            } else {
                fail();
            }
        });
    }

    $('#my-select').kendoDropDownList({
        dataTextField: 'fullname',
        dataValueField: 'id',
        dataSource: {
            data: people
        },
        select: function(e) {
            let selectedItem = e.dataItem;
            let widgetInstance = e.sender;
            let id = e.dataItem.get(widgetInstance.options.dataValueField);
            e.preventDefault();
            confirmAsync(function() {
                widgetInstance.value(id);
            }, function() {
                // nothing to do because of prevent default. 
            });
        }
    });
</script>