How to cancel window closing in MVVM WPF application

前端 未结 3 900
滥情空心
滥情空心 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:06

    I'm not an MVVM expert, but in my opinion Yusufs' answer isn't quite MVVM. On the other hand Torpederos answer is a bit complicated for only close cancellation. Here is my approach. In this example I subscribed to the closing event, but it is always cancelled

    private void OnClosing(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
        return;
    }
    

    In the XAML I added this

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    
        
            
        
    
    

    And finally in the view model

    public ICommand Close { get; set; }
    Close = new RelayCommand(CommandClose);
    private void CommandClose(object sender)
    {
        if (Dirty)
        {
            // Save your data here
        }
        Environment.Exit(0);
    }
    

    In this approach the the closing event is triggered first. That cancels the closing. After that the interaction trigger is invoked and triggers the code in the view model via the RelayCommand. In the view model I can use the Dirty flag that is not accessible in the view.

提交回复
热议问题