How to use disposable view models in WPF?

后端 未结 2 1457
南旧
南旧 2021-02-07 21:15

How do I ensure view models are properly disposed of if they reference unmanaged resources or have event handlers such as handling elapsed on a dispatcher timer. In the first c

2条回答
  •  旧巷少年郎
    2021-02-07 22:12

    I accomplished this by doing the following:

    1. Removing the StartupUri property from App.xaml.
    2. Defining my App class as follows:

      public partial class App : Application
      {
          public App()
          {
              IDisposable disposableViewModel = null;
      
              //Create and show window while storing datacontext
              this.Startup += (sender, args) =>
              {
                  MainWindow = new MainWindow();
                  disposableViewModel = MainWindow.DataContext as IDisposable;
      
                  MainWindow.Show();
              };
      
              //Dispose on unhandled exception
              this.DispatcherUnhandledException += (sender, args) => 
              { 
                  if (disposableViewModel != null) disposableViewModel.Dispose(); 
              };
      
              //Dispose on exit
              this.Exit += (sender, args) =>
              { 
                  if (disposableViewModel != null) disposableViewModel.Dispose(); 
              };
          }
      }
      

提交回复
热议问题