How do you intercept the hardware/system back button?
Short answer
Override OnBackButtonPressed on a Page (Android hardware back) and return true to indicate you've handled it (prevent default). For Shell navigation interception, use the Navigating event.
Advertisement
AModel answer
Override OnBackButtonPressed on a Page (Android hardware back) and return true to indicate you've handled it (prevent default). For Shell navigation interception, use the Navigating event. iOS has no hardware back, so also handle the navigation-bar back through Shell or a custom toolbar item.
protected override bool OnBackButtonPressed()
{
if (HasUnsavedChanges) { PromptDiscard(); return true; }
return base.OnBackButtonPressed();
}Real-world example
An editor asks to confirm discard when the user presses Android's back button with unsaved edits.
Likely follow-ups
- What does returning true do? | Does iOS have a hardware back?
Related topics