Reputation: 5480
How do I stop my application from going back when the user clicks on the "Cancel" button after hitting the back button?
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
this.NavigationService.GoBack();
}
else
{
//How to stop page from navigating
}
}
Upvotes: 1
Views: 1093
Reputation: 459
A little more ..
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (e.Cancel)
return;
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
**//this line may useful if you are in the very first page of your app**
if (this.NavigationService.CanGoBack)
{
this.NavigationService.GoBack();
}
}
else
{
//Stop page from navigating
e.Cancel = true;
}
}
Upvotes: 1
Reputation: 5937
Use CancelEventArgs
to cancel the action, property Cancel.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
// If the event has already been cancelled, do nothing
if(e.Cancel)
return;
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
this.NavigationService.GoBack();
}
else
{
//Stop page from navigating
e.Cancel = true;
}
}
Upvotes: 2