How to cancel window closing in MVVM WPF application

前端 未结 3 915
滥情空心
滥情空心 2021-02-13 11:22

How can I cancel exiting from particular form after Cancel button (or X at the top right corner, or Esc) was clicked?

WPF:



        
3条回答
  •  我寻月下人不归
    2021-02-13 12:05

    You are trying to do View's work in ViewModel class. Let your View class to handle the closing request and whether it should be canceled or not.

    To cancel closing of a window you can subscribe to the Closing event of view and set CancelEventArgs.Cancel to true after showing a MessageBox.

    Here is an example:

    
    
    

    Code behind:

    private void OnClosing(object sender, CancelEventArgs e)
    {
        var result = MessageBox.Show("Really close?",  "Warning", MessageBoxButton.YesNo);
        if (result != MessageBoxResult.Yes)
        {
            e.Cancel = true;
        }
    
        // OR, if triggering dialog via view-model:
    
        bool shouldClose = ((MyViewModel) DataContext).TryClose();
        if(!shouldClose)
        {
            e.Cancel = true;
        }
    }
    

提交回复
热议问题