Windows Phone 8.1 override back button on a certain page

此生再无相见时 提交于 2019-11-28 07:06:19
Rob Caplan - MSFT

Consider hard if this is what you really want to do. A more user friendly flow would be to save the data and let the user back out of the app and return. Also consider what happens if the user exits in a different way such as the window or camera button.

That said, the code you list will work if that's the only navigation handling that you have (try it in the BlankPage template). I suspect that it's not the only and you're using something like the NavigationHelper from the fuller templates such as BasicPage. In that case the NavigationHelper's GoBackCommand is probably triggering and calling Frame.GoBack.

You can override this behaviour by setting your own RelayCommand on the NavigationHelper's GoBackCommand property:

RelayCommand _checkedGoBackCommand;
public BasicPage1()
{
    this.InitializeComponent();

    this.navigationHelper = new NavigationHelper(this);
    this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
    this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

    _checkedGoBackCommand = new RelayCommand(
                                    () => this.CheckGoBack(),
                                    () => this.CanCheckGoBack()
                                );

    navigationHelper.GoBackCommand = _checkedGoBackCommand;
}

private bool CanCheckGoBack()
{
    return true;
}

private async void CheckGoBack()
{
    Debug.WriteLine("CheckGoBack"); 
    MessageDialog dlg = new MessageDialog("Are you sure you want to quit you will loose all your work ?", "Warning");
    dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(CommandHandler1)));
    dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler(CommandHandler1)));

    await dlg.ShowAsync();
}

private void CommandHandler1(IUICommand command)
{
    var label = command.Label;
    switch (label)
    {
        case "Yes":
            {
                Application.Current.Exit();
                break;
            }
        case "No":
            {
                break;
            }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!