Reputation: 1035
I have two pages (MainPage and page1). when the user is in the page1, if the user press back key, following message should pop up : "Are you sure that you want to exit? "
Thus, if user press OK then it should navigate to another page, if the user press Cancel it should stay in the same page. Here is my Code:
This code is written in Page1.Xaml:
Protected override void OnBackKeyPrss(System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult res = MessageBox.show("Are you sure that you want to exit?",
"", MessageBoxButton.OkCancel);
if(res==MessageBoxResult.OK)
{
App.Navigate("/mainpage.xaml");
}
else
{
//enter code here
}
}
However, when I am pressing cancel it is still navigating to mainpage.xaml. How can I solve this problem?
Upvotes: 2
Views: 494
Reputation: 2916
For the classic "Are you sure you want to quit?" message dialog, you need to override the OnBackKeyPress
event and use yourown MessageBox
in it :
protected override void OnBackKeyPress(CancelEventArgs e)
{
var messageBoxResult = MessageBox.Show("Are you sure you want to exit?",
"Confirm exit action",
MessageBoxButton.OKCancel);
if (messageBoxResult != MessageBoxResult.OK)
e.Cancel = true;
base.OnBackKeyPress(e);
}
But I would like to point the navigation logic and why you're doing something wrong. If I understood correctly, MainPage
is the first page which is shown when the app is launched and Page1
is shown when navigating to it from MainPage
.
When navigating backwards, instead of
NavigationService.Navigate(new Uri("MainPage.xaml", UriKind.Relative));
(you didn't write like this, but at least this is what you should have written, with correct syntax but wrong logic)
should be done like this :
NavigationService.GoBack();
This is because while navigating within your app, there will be a NavigationStack
(with the navigated pages) which will only have actions of Push()
(Navigation forwards) instead of also Pop()
(Navigation backwards).
For more navigation information in Windows Phone, click here.
Upvotes: 0
Reputation: 6590
try this
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Are you sure that you want to exit?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
e.Cancel = true;
else
base.OnBackKeyPress(e);
}
Upvotes: 0
Reputation: 39988
Use e.Cancel = true;
to cancel back navigation.
Please correct me if I'm wrong. Your code is looking messed up. I think you last page/back page is mainpage.xaml
and in OK
you are again navigating to this page. If this is the case then there is no need of navigating again you can use below code.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?",
"", MessageBoxButton.OKCancel);
if (res != MessageBoxResult.OK)
{
e.Cancel = true; //when pressed cancel don't go back
}
}
Upvotes: 1