2011-08-08 5 views
11

管理対象外のリソースを参照しているか、ディスパッチャタイマーで処理が経過したなどのイベントハンドラがあると、ビューモデルが正しく処分されるようにするにはどうすればよいですか。最初のケースでは、ファイナライザーはオプションですが、理想的ではありませんが、後者では決して呼び出されません。ビューモデルに添付されたビューがなくなったことをどのようにして知ることができますか?WPFで使い捨てビューモデルを使用するには?

+0

私は作品を考える解決策を持っているとして、私は自分の質問に答えましたが、私は誰かが私にはるかに良いを与えることを願っています私は受け入れられた答えとしてマークすることができます。 – ForbesLindesay

答えて

5

可能ワン、ではないが完璧なソリューション:

、ビューのコンストラクタで、この拡張メソッドを使用して、ビューモデルにIDisposableを実装します。

public static void HandleDisposableViewModel(this FrameworkElement Element) 
    { 
     Action Dispose =() => 
      { 
       var DataContext = Element.DataContext as IDisposable; 
       if (DataContext != null) 
       { 
        DataContext.Dispose(); 
       } 
      }; 
     Element.Unloaded += (s, ea) => Dispose(); 
     Element.Dispatcher.ShutdownStarted += (s, ea) => Dispose(); 
    } 
7

私は、次の手順を実行して、これを達成:

  1. App.xamlからStartupUriプロパティを削除します。
  2. 次のように私のアプリクラスの定義:

    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(); 
         }; 
        } 
    } 
    
関連する問題