Reputation: 317
I have 2 page, MainPage and SettingsPage. In the MainPage there is a button that when clicked it allows to get to the SettingsPage using this code:
Frame.Navigate(typeof(SettingsPage));
Now I want that on the second page when the user clicks the back button the application go back to the MainPage.
I've tried by adding the following code:
public SettingsPage()
{
this.InitializeComponent();
SystemNavigationManager.GetForCurrentView().BackRequested += SettingsPage_BackRequested;
}
private void SettingsPage_BackRequested(object sender, BackRequestedEventArgs e)
{
if (this.Frame.CanGoBack)
{
this.Frame.GoBack();
}
e.Handled = true;
}
The application go back to the MainPage but the SettingsPage_BackRequested event continues to work so if I click the back button on the MainPage the app doesn't close.
How can i handle the backbutton in my application?
Upvotes: 0
Views: 781
Reputation: 2105
I suggest that you move your navigation code to the App object. The great news with the SystemNavigationManager is that you can centralize your code and make the default navigation process very easy to do. Here's a simplified version
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
rootFrame.Navigated += OnNavigated;
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
...
}
private void OnNavigated(object sender, NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
((Frame)sender).CanGoBack ?
AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
e.Handled = true;
rootFrame.GoBack();
}
}
For more details, check this great tutorial
http://www.wintellect.com/devcenter/jprosise/handling-the-back-button-in-windows-10-uwp-apps
Upvotes: 1