0

I am developing Windows Phone 8.1 app with MVVM.

I have base view model class which contains Navigation Service as below:

 public abstract class BaseViewModel : INotifyPropertyChanged
    {
        protected readonly INavigationService NavigationService;
        //....
    }

There is my navigation service class:

  public class NavigationService : INavigationService
    {
        public void Navigate(Type destinationPage)
        {
            ((Frame)Window.Current.Content).Navigate(destinationPage);
        }

        public void Navigate(Type desitnationPage, object parameter)
        {
            ((Frame)Window.Current.Content).Navigate(desitnationPage, parameter);
        }

        public void GoBack()
        {
            ((Frame)Window.Current.Content).GoBack();
        }
    }

Everything is working fine when I am binding commands from XAML. There is problem when I want to override BackButton. I have also created base page model which also contains NavigationService. Each page has an overridde pf BackPressed as below:

public class BasePage : Page
    {
        protected INavigationService NavigationService => ComponentManager.GetInstance<INavigationService>();

        public BasePage()
        {
            //...
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            HardwareButtons.BackPressed += HardwareButtons_BackPressed;
        }
       protected virtual void HardwareButtons_BackPressed(object sender,    BackPressedEventArgs e)
        {
            //Frame.Navigate(typeof(MainPage));
            (this.DataContext as BaseViewModel)?.Back.Execute(sender);
        }
}

As you see in HardwareButtons_BackPressed method I've tried to make it in to ways but none is workings. Every time I press back button application crashes without any error.

Tseng
  • 61,549
  • 15
  • 193
  • 205
miechooy
  • 3,178
  • 12
  • 34
  • 59
  • Have a look at http://stackoverflow.com/questions/24335925/windows-phone-8-1-universal-app-terminates-on-navigating-back-from-second-page – Bugs Oct 17 '16 at 08:06

1 Answers1

0

I don't think the app is crashing, it's just exiting because that is the default behaviour of the back button.

What you need to do is flag that you've handled the back button by adding this line of code in your BackPressed event handler:

e.Handled = true;
Roger Hartley
  • 684
  • 3
  • 11