我目前正在为Windows 10开发一个应用程序,我想在我的应用程序上实现一个后退按钮事件。当我按下Frame1上的后退按钮时,应用程序就会关闭,就像我想做的那样。当我在Frame2,导航到Frame3,我按后退按钮,应用程序关闭自己。
我想要的是Frame3上的后退按钮事件使Frame3返回到Frame2,当我在Frame2上按后退按钮时,终止应用程序。
在我的App.xaml.cs上
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(Frame1), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}在我的Frame1.xaml.cs上
private void 1_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
{
Frame frame1 = Window.Current.Content as Frame;
if (frame1 != null)
{
e.Handled = true;
Application.Current.Exit();
}
}在我的Frame2.xaml.cs上
private void 2_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
{
Frame frame2= Window.Current.Content as Frame;
if (frame2 != null)
{
e.Handled = true;
Application.Current.Exit();
}
}在我的Frame3.xaml.cs上
private void 3_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
{
Frame frame3= Window.Current.Content as Frame;
if (frame3.CanGoBack)
{
e.Handled = true;
frame3.GoBack();
}
}发布于 2015-10-16 07:48:43
这是因为您添加到BackPressed事件中的事件处理程序将按FIFO顺序触发,因此您的事件根据您的代码处理堆栈:
当您在Page1时:
1.关闭应用程序
当您导航到Page2时:
1.关闭应用程序 2.关闭应用程序
从Page3导航到Page2时:
1.关闭应用程序 2.关闭应用程序 3.Goback到最后一页
因此,当您按下Page3中的后退按钮时,第一个处理程序应该首先启动,这意味着它是close app而不是going back到最后一个页面。
那怎么解决这个问题?
在你的每一页中:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}这意味着,每当您离开此页面时,您都会取消对Backpressed事件的注册,而当您输入一个页面时,您将注册一个新的页面以使其工作。
https://stackoverflow.com/questions/33162478
复制相似问题