So I just learned that we can put a WPF UserControl
to a windows Form
using ElementHost
control. If that windows form control was disposed, will the WPF user control be disposed too?
Asked
Active
Viewed 2,140 times
1

Reza Aghaei
- 120,393
- 18
- 203
- 398

Kokombads
- 450
- 2
- 9
- 23
-
It is same. All object oriented programming language same. WPF usercontrol disposable. – ebattulga Sep 16 '16 at 03:56
-
@ebattulga WPF UserControl is not `IDisposable` by default and will not `Dispose`. Take a look at this post: [Proper cleanup of WPF user controls](http://stackoverflow.com/questions/1550212/proper-cleanup-of-wpf-user-controls). The `Dispose` method of the `ElementHost` control checks if the `Child` is `IDisposable` then calls its `Dispose` method. So if you need to `Dispose` anything, you should implement `IDisposable` interface. – Reza Aghaei Sep 18 '16 at 21:24
1 Answers
3
If your WPF UserControl
is IDisposable
the answer is yes, otherwise no.
In the source code for Dispose
method of ElementHost
class which hosts a WPF UserControl
, you can see this:
IDisposable child = this.Child as IDisposable;
if (child != null)
{
child.Dispose();
}
Which means the Child
will be disposed, if it's IDisposable
.
Note
WPF doesn't rely on IDisposable
interface for resource cleanup. But since the UserControl
will be used in a Windows Forms Project in an ElementHost
control which supports IDisposable
pattern, you can rely on IDisposable
pattern if you need to perform some resource clean up. But if it was a WPF project, you should use WPF mechanisms for resource clean up.

Reza Aghaei
- 120,393
- 18
- 203
- 398