tags:

views:

43

answers:

2

Hi!

I have a simple user control with the following content:

<Grid x:Name="LayoutRoot">

  <Button x:Name="btnOpenGenericPage" Click="btnOpenGenericPage_Click" Content="Open"/>

</Grid>

I understand how the click event handler is created and wired up -> on the InitializeComponent method of the .g.cs class the System.Windows.Application.LoadComponent method is called and all the magic is done.

However, once this control is removed from the VisualTree, I don't seem to understand if the unwiring of the event is ocurring. If yes, who takes care of this? Are there any situations where the event won't be unwired? Can someone please shed some light on this issue?

Many thanks in advance, Bruno.

+1  A: 

Visual Studio unwires it, by removing it from the generated code. The method may remain in the code-behind file, but it's disconnected and doesn't run.

Cyberherbalist
I think you've mis-understood the question, the question relates to the removal of a control from the tree during __runtime__.
AnthonyWJones
I'm sorry if I haven't been clear. But I would like to understand who is responsible for unwiring the event handler when the control is removed from the tree in runtime - and exactly at which point is this occurring.
Bruno
+1  A: 

It won't unwire itself. You will have to do that yourself:-

btnOpenGenericPage.click -= btnOpenGenericPage_Click

not only that but of you want to make sure that btOpenGenericPage is released you would need:-

btnOpenGenericPage = null;

Of course if the Usercontrol on which btnOpenGenericPage is sited is itself being removed from the tree such that it becomes elligible for garbage collection then you wouldn't normally need to do anything.

AnthonyWJones
As far as I understand, the EventHandler will hold a reference to the UserControl where the btnOpenGenericPage is sited. Given so, since this reference will be alive if we don't unwire the event, how will the UserControl be elligible for GC? Many thanks!
Bruno
@Bruno: An event handler having a reference to the `UserControl` doesn't automatically mean that it can't be collected. If you can't trace back through the references to something that is currently referenced at the global level or in one the thread stacks then the item is elligable for collection. For example if you have this circular reference UserControl->Button->ClickEvent->UserControl the `UserControl` and the `Button` can be collected if there is nothing else referencing them. The fact that they reference each other doesn't matter, they are unreachable by normal code.
AnthonyWJones
Hi Anthony, thanks for your clarification, now I seem to understand the problem I have in hands. Cheers.
Bruno