views:

217

answers:

1

Does this line leak if we remove TextBox from the visual and logical tree? To me this leaks because Mouse.MouseDown has a reference on myHandler and nothing is done to remove the handler.

<TextBox Mouse.MouseDown="myHandler" />

I'm not sure, because this code is common practice.

+2  A: 

Does it leak? That XAML translates directly into the following code (see the Window1.g.cs file generated in the obj directory)

((System.Windows.Controls.TextBlock)(target)).AddHandler(System.Windows.Input.Mouse.MouseDownEvent, new System.Windows.Input.MouseButtonEventHandler(this.TextBlock_MouseDown));

So, what's actually happening is that we are adding a reference of "this" (in my case an instance of Window1) to the TextBlock. The syntax you see in the XAML is actually the syntax of attaching a RoutedEvent handler for either Routed Events or Attached Events. It just happens that the syntax makes it looks like you are assigning some reference. Take a look at this: Routed Events Overview and Attached Events Overview.

Edit: In conclusion, it doesn't leak. :)

Edit2: If you have any reference to the TextBlock, this will leak. But if when you switch out the TextBlock, you make sure that there is no more references to the element, you'll be fine.

siz
Ok, so this means there is no leak. Thanks for your answer !
Nicolas Dorier
If a reference to the TextBlock is preserved somewhere else in the code this will leak. Please note that Routed Events are not weak events.
ligaz
Yes, but since there isn't one, that particular line of code won't leak. :) I'll edit to reflect this detail.
siz