按"X"按钮时允许取消

Mat*_*att 2 c# wpf xaml

当用户在主窗口中按下"X"时,我会出现以下对话框:

 -- Save Changes --------------------------
|                                          |
|  Do you want to save changes?            |
|                                          |
|                                          |
|    |Don't Save|      |Cance|   |Save|    |
|__________________________________________|
Run Code Online (Sandbox Code Playgroud)

我无法实现取消按钮.在用户点击取消后,我无法弄清楚如何告诉主窗口不要关闭.我通过窗口的"Closing"命令/方法提示用户使用此对话框.

sal*_*uce 10

在结束事件中,您需要将event属性设置Cancel为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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


Tud*_*dor 5

调用的处理程序方法有一个表示事件args的参数(类型为CancelEventArgs,让我们调用它e.e.Cancel = true在处理程序中设置以防止默认行为.