tags:

views:

72

answers:

2

I have a member in the WPF code behind that is disposable (meaning it implements the IDisposable interface)

I do not see any Dispose method I can override from UserControl in WPF so I can dispose of the member in my wpf usercontrol

What is the correct way to dispose of a member in a WPF usercontrol?

It's a usercontrol that wraps a private member which implements the IDisposable interface. Thus I need to dispose of that member somewhere. In the tradition winform, the usercontrol had a Dispose method that could be overriden so that in the override I could dispose of the private member. But in the WPF usercontrol, there is no such thing. So I was wondering where can I dispose of the private member in the wpf usercontrol.

My question is not about disposing the usercontrol, but where to dispose one of its private member which implement the IDisposable interface

+1  A: 

You could use the Unloaded event of the UserControl to do your resource cleanup.

MrDosu
Is this the standard way of doing it ?
pdiddy
The standard way would be to eliminate the code behind through something like a MVVM/MVP pattern or the like and deal with the Disposing on a higher level.
MrDosu
A: 

UPDATE

When you call into your private member that implements IDisposable, can you use using? This way, it gets disposed of automatically. I haven't personally done it this way in a UserControl, but it might do the trick. e.g.

using( MyPrivateDisposable mpd = new MyPrivateDisposable) {
    mpd.MethodA();
}

old answer

If you can't call Dispose(), the problem is that your UserControl doesn't inherit from Disposable(). UserControl itself is not derived from it so you have to explicitly make your WPF control inherit from it, i.e.

public class MyControl : UserControl, IDisposable {...}

See the UserControl base types here:

alt text

Once you implement IDisposable, you can call it. But as I wrote in my comment to your question, I think you need to post more information about this class. Ask yourself if you really need to call Dispose() on it... i.e. does your UserControl access handles, or use unmanaged code? If not, I don't see why you would have to call Dispose() on it unless you really wanted the GC to clean it up.

Dave
I understand that usercontrol in wpf doesn't implement IDisposable. But my question is not about disposing of the usercontrol ....
pdiddy
Ok, it looks like you edited your question again, thanks, I see that you do implement IDisposable.
Dave
@pdiddy ok, now I understand what you're asking.
Dave
Thanks for answering. But in my case I don't want to use using for different reason. So I do need to keep a private member and dispose it later on ...
pdiddy
okie, no problem. As long as you've got a solution to your problem that works, it's all good. :)
Dave