How to prevent user from navigating away or close the app when there are unsaved changes? RRS feed

  • Question

  • Hi there,

    I'm building an windows 8.1 app, using MVVM and a XAML form. I'd like to pop up a dialog window when there is unsaved change in the page.

    Here is my code for navigating:

    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); if (model.IsDirty()) { var msg = new MessageDialog("You have unsaved changes, save before leaving?"); msg.Commands.Add(new UICommand("Yes", (UICommandInvokedHandler) => {

    e.Cancel = true; SaveButton_Click(null, null); })); msg.Commands.Add(new UICommand("No", (UICommandInvokedHandler) => { e.Cancel = false; })); msg.DefaultCommandIndex = 0; msg.CancelCommandIndex = 1; msg.ShowAsync(); } }

    It doesn't work because showAsync is an async method, the page is navigated away before the dialog pops up. Is there a way to stop navigating away until we get a feedback from user?

    For prompting upon exiting, I learn from here msdn.microsoft.com/en-us/library/windows/apps/hh464925.aspx#close that there is no way to detect a closing event, is there a way to pop up a same dialog box upon exiting?

    Wednesday, May 6, 2015 7:41 AM


All replies

  • What's the behavior which allows the navigation to occur? What I mean is that you likely have a button that calls Frame.Navigate. You should handle the form validation before calling Frame.Navigate and avoid this problem.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Wednesday, May 6, 2015 5:14 PM
  • Matt's post addresses navigation within the app.

    There isn't a way to block the user from exiting or closing the app. You should save the changes and allow the user to revert them rather than requiring an active dialog to save.


    Wednesday, May 6, 2015 8:13 PM