1

How can I cancel current page to navigate back when back button pressed in Windows 10 UWP?

In windows Phone 8 or 8.1 Silverlight I can write this code and handle it

private void PageBackKeyPress(object sender, CancelEventArgs e)
 {
    if (MGMethods.DisplayMessageWithButton(MessageText))
    {
       //Can Navigate Back
    }
    else
    {
      //Stop to Navigate back
      e.Cancel = true;
    }
 }

But , in windows 10 How can I do this same logic.

I have tried it but it doesn't work.

Maulik Shah
  • 673
  • 7
  • 19
  • Possible duplicate of [Handling Back Navigation Windows 10 (UWP)](https://stackoverflow.com/questions/31832309/handling-back-navigation-windows-10-uwp) – Vagner Gon Jan 23 '18 at 11:52

2 Answers2

2

The SystemNavigationManager lets you respond to user presses of the system provided back button such as a hardware button. To enable your app to respond to the system back-navigation event, call GetForCurrentView to get the SystemNavigationManager object associated with the current view, then register an event handler for the BackRequested event. Your app will receive the event only of it's the foreground app. If you handle the BackRequested event, set the BackRequestedEventArgs.Handled property to true to mark the event as handled. If you don't mark the event as handled, the system decides whether to navigate away from the app (on the Mobile device family) or ignore the event (on the Desktop device family):

Windows.UI.Core.SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += (s,a) =>
{
    Debug.WriteLine("BackRequested");
    if (Frame.CanGoBack)
    {
        Frame.GoBack();
        a.Handled = true;
    }
}

Source: MSDN

Kristian Vukusic
  • 3,284
  • 6
  • 30
  • 46
0

For hardware Back button you can use BackPressed event:

HardwareButtons.BackPressed += HardwareButtons_BackPressed;
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
        {
             e.Handled = true;
        }

Or clear the Stack if other stack items not important:

this.Frame.BackStack.Clear();

Or:

var frame = Window.Current.Content as Frame;
frame.BackStack.Clear();
n.y
  • 3,343
  • 3
  • 35
  • 54