title: Overriding the Back Button in Prism for Windows Phone 8.1 Runtime
body: <p>I'm using the Prism MVVM library for WinRT in a Windows Phone 8.1 project. Is it possible to prevent back navigation via the phone's back button and handle the back button press in the ViewModel?</p>
  
  <p>Concrete scenario:</p>
  
  <ul>
  <li>The user can select one item (the "active" item) from a list of items - like a player in a game. That item is a reference for the rest of the app's functionality, e.g. database queries.</li>
  <li>Selecting one item returns the user to the previous (main) page.</li>
  <li>In the same list, the user can also delete an item that is no longer needed. It should be possible to delete all items.</li>
  </ul>
  
  <p>Problem: If the user deletes the active item or the last item and then taps the back button, I end up having an invalid active item.</p>
  
  <p>To prevent that, I'd like to cancel the back button navigation and prompt the user to select or create another active item, ideally from the ViewModel.</p>
  
  <hr>
  
  <p><strong>Update:</strong> I have now added an event handler to the App.xaml.cs based on how I understood Nate's comment below. This should override it application-wide:</p>
  
  <pre><code>private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
  {
      Frame currentFrame = Window.Current.Content as Frame;
      if (currentFrame == null)
      {
          return;
      }
      if (currentFrame.Content is SelectionPage)
      {
          e.Handled = true;
      }
      else if (currentFrame.CanGoBack)
      {
          currentFrame.GoBack();
          e.Handled = true;
      }
  }
  </code></pre>
  
  <p>and subscribing to the event in the constructor:</p>
  
  <pre><code>#if WINDOWS_PHONE_APP
          HardwareButtons.BackPressed += HardwareButtons_BackPressed;
  #endif
  </code></pre>
  
  <p>This seems to be handling the back button press just fine but it does not stop the existing navigation. So it goes back in any case and twice in the default case.</p>