views:

54

answers:

3

Hello,

I dynamically create UserControls using Reflection: UserControl myConmtrol = (UserControl)Activator.CreateInstance(t);

The UserControl may handle a Closing event but I do not know the name of the handler.

When the Window hosting the UserControl closes I remove the UserControl from its parent Window and it disappears from the Window: Everything seems OK.

But if I open and close again the UserControl I can see in the debugger the Closing event is handled twice, one time by the current UserControl but also by the previous UserControl that is still alive.

Theorically the UserControl being no longer referenced should be GarbageCollected. How can I force it to be Killed/Deleted/Disposed ? At least is there a way to forbid it handles events ?

Thanks

A: 

Not sure without more detail but i would start and check if you have any event handlers that isn't removed

http://stackoverflow.com/questions/1076401/do-i-need-to-remove-event-subscriptions-from-objects-before-they-are-orphaned

rudigrobler
OK, what I suspected, thanks for the confirmation.
qay
But how to use RemoveHandler when I do not know the name of the handler ? Any other methjod to remove handlers ?
qay
A: 

I had to cope with the same situation in Winforms where I dynamically create a user control inside another user control (Let's say a "DynControl" inside "HostControl").

There is no Closing event in "HostControl". So I used the Disposed event of HostControl to release resources :

this.Disposed += (s, e1) => 
{
  DynControl.Click -= += new EventHandler(MyClickHandler);
  this.Controls.Remove(DynControl);
  DynControl.Dispose();
};
controlbreak
Thanks. But no Dispose method for a WPF UserControl ...
qay
A: 

Answer about removing handlers without knowing their names:

public void RemoveHandlerOfUserControl(UserControl uc)
{

    MulticastDelegate dlg = MyEvent;
    Delegate[] handlers = dlg.GetInvocationList();
    foreach (Delegate d in handlers)
    {
        if (d.Target == uc)
        {
            this.RemoveHandler(MyEvent, d);
        }
    }
 }

This method must reside in the object where the event is declared.

qay