2014-03-07 59 views
0

我正在尝试为Windows Phone 8开发一个简单的应用程序,并且使用后退按钮有许多要求。由于我不想让后退按钮在返回堆栈中简单地使用GoBack,因此我想弹出一个消息框来警告用户此操作将使他回到主菜单。试图覆盖NavigationMode.Back

问题是,此页面必须重新加载一段时间,以下代码在1次重新加载后不能正常工作。该消息框打开多次。我重新载入的次数越多,出现的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中有2个按钮。

并且代码将不会工作,直到您第一次重新加载页面,因为它不是NavigatedTo当它的头版(在我的实际项目中没有问题)。

我做错了什么线索?

注:我不想更改事件处理程序(例如OnBackKeyPress)。我有兴趣了解我选择的处理程序(NavigationService.Navigating,NavigationMode.Back)是怎么回事。由于

+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

+0

对不起, – Inox

回答

1

更新以下是澄清追问

更改您的导航事件处理程序将意味着该事件在堆栈

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

不再neccessary

每一页上,不会触发更多的信息

忽略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); 
} 
+0

谢谢,但这只是假装问题不存在。我重写OnBackKeyPress,但它带来了更多的问题。长话短说,我使用的一些对象(类似于messagebox)(来自Coding4Fun工具包)在BackButton上有监听器,几乎不可能(无需进入工具箱代码并删除这些监听器)使其工作。 – Inox

+0

您需要编辑您的问题以包含该信息,因为您没有解释这是您遇到的问题。 –

+0

创建主题以更好地理解一个概念(NavigationService.Navigating处理程序),希望现在更清楚。 – Inox