【问题标题】:Windows Phone: How to stay in the Current page rather than navigating to another page?Windows Phone:如何停留在当前页面而不是导航到另一个页面?
【发布时间】:2013-08-07 03:14:06
【问题描述】:

我有两个页面(MainPage 和 page1)。当用户在 page1 中时,如果用户按返回键,应弹出以下消息:“您确定要退出吗?”

因此,如果用户按下 OK,那么它应该导航到另一个页面,如果用户按下 Cancel,它应该停留在同一页面。这是我的代码:

这段代码是用Page1.Xaml编写的:

Protected override void OnBackKeyPrss(System.ComponentModel.CancelEventArgs e)
{
      MessageBoxResult res = MessageBox.show("Are you sure that you want to exit?",
      "", MessageBoxButton.OkCancel);
      if(res==MessageBoxResult.OK)
      {
         App.Navigate("/mainpage.xaml");
      }
      else
      {
            //enter code here
      }

}

但是,当我按下取消时,它仍在导航到 mainpage.xaml。我该如何解决这个问题?

【问题讨论】:

    标签: c# windows-phone-7 windows-phone-8


    【解决方案1】:

    使用e.Cancel = true; 取消返回导航。

    如果我错了,请纠正我。你的代码看起来很乱。我认为您的最后一页/后一页是mainpage.xaml,而在OK 中,您将再次导航到此页面。如果是这种情况,则无需再次导航,您可以使用以下代码。

    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?",
        "", MessageBoxButton.OKCancel);
        if (res != MessageBoxResult.OK)
        {
            e.Cancel = true;  //when pressed cancel don't go back
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个

      protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
      {
          if (MessageBox.Show("Are you sure that you want to exit?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
              e.Cancel = true;
          else
              base.OnBackKeyPress(e);
      }
      

      【讨论】:

        【解决方案3】:

        对于经典的“您确定要退出吗?”消息对话框,您需要覆盖OnBackKeyPress 事件并在其中使用您自己的MessageBox

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            var messageBoxResult = MessageBox.Show("Are you sure you want to exit?", 
                                                   "Confirm exit action",
                                                   MessageBoxButton.OKCancel);
            if (messageBoxResult != MessageBoxResult.OK)
                e.Cancel = true;
            base.OnBackKeyPress(e);
        }
        

        但我想指出导航逻辑以及您做错事的原因。如果我理解正确,MainPage 是应用程序启动时显示的第一页,Page1 是从MainPage 导航到它时显示的第一页。

        向后导航时,而不是

        NavigationService.Navigate(new Uri("MainPage.xaml", UriKind.Relative));

        (你没有这样写,但至少这是你应该写的,语法正确但逻辑错误)

        应该这样做:

        NavigationService.GoBack();
        

        这是因为在您的应用程序中导航时,将有一个 NavigationStack(带有导航页面),它只有 Push()(向前导航)而不是 Pop()(向后导航)的操作。

        有关 Windows Phone 中的更多导航信息,click here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-17
          • 2019-03-17
          • 1970-01-01
          • 1970-01-01
          • 2013-05-11
          • 2022-01-24
          相关资源
          最近更新 更多