Why does unloaded event of window do not fire in WPF?

后端 未结 3 494
滥情空心
滥情空心 2021-01-17 18:26

In my WPF application I have created a window and show it as a dialog by calling it by the method ShowDialog(). But when I close the window by Close() method the Unloaded ev

3条回答
  •  别那么骄傲
    2021-01-17 18:44

    I stumbled on this work-around by accident. I happened to create another window in my code and therefore did not see the issue of Unloaded Event not firing in WPF.

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
    
            new Window(); //<-- this will make Unloaded Event to trigger in WPF
        }
    }
    

    The work-around also works in MVVM pattern!

    Ignore the rest of the code below if you don't do MVVM pattern.

    XAML (Requires reference to System.Windows.Interactivity)

    
    
      
          
              
          
      
    
    

    Code behind

        public ICommand WindowUnLoadEventHandler
        {
            get
            {
                if (_windowUnload == null)
                {
                    _windowUnload = new MyDelegateCommand(ExecuteWindowUnLoadEventHandler);
                }
                return _windowUnload;
            }
        }
    
        private void ExecuteWindowUnLoadEventHandler(object parameter)
        {
            //Do your thing
        }
    

    MyDelegateCommand

    public class MyDelegateCommand : ICommand
    {
        private readonly Action _execute;
    
        public MyDelegateCommand(Action execute)
        {
            this._execute = execute;
        }
    
        public void Execute(object parameter)
        {
            _execute?.Invoke(parameter);
        }
    
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    }
    
    
        

    提交回复
    热议问题