试图覆盖NavigationMode.Back

时间:2014-03-07 02:38:13

标签: c# windows-phone-8 back-button

我正在尝试为Windows Phone 8开发一个简单的应用程序,并且使用后退按钮有很多要求。由于我不希望后退按钮只是后台堆栈中的GoBack,我想弹出一个消息框来警告用户此操作会将他带回主菜单。

问题是,此页面必须重新加载一次,并且以下代码在重新加载后停止正常工作。消息框多次打开。我重新加载的次数越多,MessageBox就会出现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BackButtonTests.Resources;

namespace BackButtonTests
{
public partial class MainPage : PhoneApplicationPage
{        
    public MainPage()
    {
        InitializeComponent();            
    }

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        NavigationService.Navigating += NavigationService_Navigating;
    }

    void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
    {

        if (e.NavigationMode == NavigationMode.Back)
        {
            e.Cancel = true;
            MessageBox.Show("Quit");
        }
    }

    private void Restart_Click(object sender, RoutedEventArgs e)
    {
        NavigationService.Navigate(new Uri("/MainPage.xaml?reload=" + DateTime.Now.ToString(), UriKind.RelativeOrAbsolute));
        //Use this fake reload query with unique value as a way to "deceive" the system, as windowsphone does not support NavigationService.Reload, and using simply the Uri of the same page will not properly load everything
    }

    private void Quit_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Quit");
    }
}
}

这只是我编写的测试代码,它正好显示了我在实际项目中遇到的问题。当然有两个用xaml写的按钮。

在您第一次重新加载页面之前,代码将无法运行,因为当它是首页时它不是NavigatedTo(在我的实际项目中不是问题)。

我做错了什么线索?

注意:我对更改事件处理程序(例如OnBackKeyPress)不感兴趣。我有兴趣了解我选择的处理程序(NavigationService.Navigating,NavigationMode.Back)发生了什么。感谢

1 个答案:

答案 0 :(得分:1)

更新了以下有助于澄清任务的其他信息

将导航事件处理程序更改为意味着不会在堆栈中的每个页面上触发事件

void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
{
    NavigationService.Navigating -= NavigationService_Navigating;
    if (e.NavigationMode == NavigationMode.Back)
    {
        e.Cancel = true;
        MessageBox.Show("Quit");
    }
}

不再需要

覆盖OnBackKeypress而不是导航

 protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
 {
   var DoYouWantToQuit = MessageBox.Show("Are you sure you want to Quit", "Quit", MessageBoxButtons.OkCancel);
   if (DoYouWantToQuit != MessageBoxButton.Ok)
   {
      e.Cancel = true
   }
   base.OnBackKeyPress(e);
 }