Search code examples
c#wpfwinformsuser-controlsdispose

Will the WPF user Control be Disposed if used inside a Windows Form that will be disposed?


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?


Solution

  • 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.