BackButton事件关闭应用程序Windows 10应用程序
问题描述:
我目前正在为Windows 10开发一个应用程序。我想在我的应用程序上实现后退按钮事件。当我按下Frame1上的后退按钮时,应用程序关闭,正如我想要的那样。当我在Frame2上,并导航到Frame3,然后按下后退按钮时,应用程序自行关闭。BackButton事件关闭应用程序Windows 10应用程序
我想要的是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();
}
}
答
那是因为你添加到BackPressed事件的事件处理程序将在FIFO顺序火,让你的事件根据您的代码处理堆栈是:
当你在第1页:
1.关闭应用程序
当您导航到第2页:
1.关闭应用
2.Close应用
当您从第2页转到第3页:
1.关闭应用
2.Close应用
3.Goback到最后一页
所以当你按下Page3按钮时,第一个h安德勒首先应该开火,这意味着它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事件,当你进入一个页面,你注册一个新的,使其工作。
你知道@JuniperPhoton是什么吗?谢谢你^^工作 – rydev