Hello,
I have an EditorPage which has some entries etc. which are being checked for changes, if a user tries to exit the application when on this page with unsaved changes, the prompt should be triggered, else the app can close as normal with no prompt.
You can do this by get current appeared page and add a static flag in this specific page.
For example, if you use Shell. you can get current appeared page by Page currentpage = AppShell.Current.CurrentPage;
, if you use NavigationPage. you can get current page by Page currentpage = Application.Current.MainPage.Navigation.NavigationStack.Last();
.
And I add a static flag called IsSaved like following code.
public partial class NewPage1 : ContentPage
{
public static bool IsSaved=false;
public NewPage1()
{
InitializeComponent();
}
}
In the end, we can implement it in the MauiProgram.cs like following code.
events.AddWindows(windowsLifecycleBuilder =>
{
#if WINDOWS
// Required for app title to appear on taskBar (as label)
windowsLifecycleBuilder.OnWindowCreated(window =>
{
var handle = WinRT.Interop.WindowNative.GetWindowHandle(window);
var id = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(handle);
var appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(id);
// appWindow.Title is used so that when the app is running there is a title which appears in the task bar, if this is not here it is blank.
appWindow.Title = "2Pint Config Editor";
appWindow.Closing += async (s, e) =>
{
Page currentpage = AppShell.Current.CurrentPage;
// Page currentpage //=Application.Current.MainPage.Navigation.NavigationStack.Last();
if(currentpage is NewPage1 && NewPage1.IsSaved==false)
{
var res = currentpage.GetType;
// if (res != null&& res.(NewPage1))
e.Cancel = true;
bool result = await App.Current.MainPage.DisplayAlert(
"Exit prompt",
"Are you sure you want to exit the application?",
"Yes",
"Cancel"
);
if (result)
{
App.Current.Quit();
}
}
};
});
#endif
})
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.