Reputation: 955
Is it necessary to unsubscribe events which are subscribed in Xaml WPF??. If so how can I unsubscribe the events?? In the below code I have subscribed the MouseDown and OnCellClosed Events in Xaml. If its really necessary to unsubscribe the events then how can I achieve this??
<DataTemplate x:Key="Style2">
<local:MyCellStyle2 MouseDown="MyCellStyle2_MouseDown" OnCellClosed="MyCellStyle2_OnCellClosed" />
</DataTemplate>
Update : I am using a listBox with a itemtemplate which is defined above. Each item in the list box will be displayed with the datatemplate "MyCellStyle2". This "MyCellStyle2" control has a close button and when on clicked the object is removed from the listbox's collection but the object's mousedown and OnCellClosed events (see above) are still subscribed and which will not allow the removed item to be garbage collected. How can I overcome this. Correct me if I am wrong.
Upvotes: 2
Views: 2441
Reputation: 429
No need to unsubscribe events those are create in Xaml. You need to unsubscribe events which are created in Code Behind.
eg:
this.MouseDoubleClick += UserControl1_MouseDoubleClick;
this.MouseDoubleClick -= UserControl1_MouseDoubleClick;
Upvotes: 0
Reputation: 1855
No, you don't have to unsubscribe from those events. When your window is closed everything on and of that window is disposed of, so no unsubscription is needed and no memory leak will occur. If you really want to unsubscribe from one of those events from code-behind, e.g. to turn that event off temporarily, you can do so as described in How to: Subscribe to and Unsubscribe from Events.
As to your MyCellStyle2
scenario, I still think you don't have to worry about event unsubscription. In the arrangement you describe, your Window
holds a reference to your ListBox
, which holds a reference to the item, which in turn holds references to the events exposed by your Window
, effectively holding references to your Window
. Note that it's the item that references the events, not the other way round, because when something happens it's the item that should call the corresponding event. So when the item is removed from the ListBox
, it should be garbage collected because the reference to it is released, even though it's holding references to other objects.
On the other hand, if you do observe that the items are memory leaked after they are removed, maybe there are other reasons. Most likely you're facing the problem described in this, this, and this. The cure is to implement the INotifyPropertyChanged interface.
Upvotes: 3