2
votes

When the user presses the "X" in the Main Window, I have this dialog appear:

 -- Save Changes --------------------------
|                                          |
|  Do you want to save changes?            |
|                                          |
|                                          |
|    |Don't Save|      |Cance|   |Save|    |
|__________________________________________|

I am having trouble implementing the Cancel button. I cannot figure out how to tell the Main Window not to close after the user hits Cancel. I am prompting the user with this dialog via the window's "Closing" command/method.

2

2 Answers

10
votes

In the closing event, you need to set the event property Cancel to true.

    void DataWindow_Closing(object sender, CancelEventArgs e)
    {
        MessageBox.Show("Closing called");

        // If data is dirty, notify user and ask for a response
        if (this.isDataDirty)
        {
            string msg = "Data is dirty. Close without saving?";
            MessageBoxResult result = 
              MessageBox.Show(
                msg, 
                "Data App", 
                MessageBoxButton.YesNo, 
                MessageBoxImage.Warning);
            if (result == MessageBoxResult.No)
            {
                // If user doesn't want to close, cancel closure
                e.Cancel = true;
            }
        }
    }
5
votes

The handler method that is called has a parameter which represents the event args (of type CancelEventArgs, let's call it e. Set e.Cancel = true inside the handler to prevent the default behavior.