3

If I set the DataContext of a Window to something that implements IDisposable, will it be Dispose()d when the Window is closed?

Shea Levy
  • 5,237
  • 3
  • 31
  • 42

1 Answers1

4

No!

WPF doesn't really use the IDisposable interface at all—and it can be a bit tricky to write WPF code that relies on it.

Consider using something like Caliburn Micro, an MVVM framework that supports matching views and view models (assigned to DataContext) and does support automatically calling Dispose(). Without knowing the specifics of your situation, though, CM may be a bit more than you need in your scenario.

If you're interested in why WPF doesn't use IDisposable, there are several posts on StackOverflow like this one that address this. Although this discusses why controls themselves aren't disposed, the rationale applies to the DataContext too, since it's just an inherited property of the control.

Community
  • 1
  • 1
Olly
  • 5,966
  • 31
  • 60