如果 View 模型引用非托管资源或具有事件处理程序(例如在调度程序计时器上进行处理),我如何确保正确处理它们。在第一种情况下,终结器是一种选择,虽然不理想,但在后一种情况下,它永远不会被调用。我们如何知道何时不再有 View 附加到 View 模型。

最佳答案

我通过执行以下操作来完成此操作:

  • 从 App.xaml 中删除 StartupUri 属性。
  • 定义我的 App 类如下:
    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();
            };
        }
    }
    
  • 关于c# - 如何在 WPF 中使用一次性 View 模型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6983801/

    10-13 05:57