Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events in ViewModel with System.Windows.Interactivity.EventTrigger, is it weak referencing?

I have in my ViewModel an event.

public class MyViewModel:ViewModelBase
{
     ...
     public event EventHandler SomethingChanged;

     private void FireEvent()
     {
          if (SomethingChanged != null)
              SomethingChanged(this, EventArgs.Empty);
     }
     ...
}

in my View, I used the EventTrigger to listen to the Event to invoke an action.

 <i:Interaction.Triggers>            
        <i:EventTrigger EventName="SomethingChanged" SourceObject="{Binding}">
            <i:SomeAction/>
        </i:EventTrigger>
 </i:Interaction.Triggers>

It works perfectly fine. However I'm curious if there is a possibility of memory leak? As my View is created on demand, meaning the control is added and removed from the Visual tree based on the user. The source object (ViewModel) has a longer lifetime than the listener (View). Therefore, using the above code, will the event still have a strong reference to the removed listener(View)?

like image 319
icube Avatar asked Nov 04 '22 05:11

icube


1 Answers

In the OnDetaching of the EventTriggerBase, it calls the following code:

 this.OnSourceChanged(this.Source, null);

This means that the source is being set from Source to null and the event is unsubscribed. No memory leaks when the view is correctly unloaded which means the Detach method is being called.

like image 142
Geert van Horrik Avatar answered Nov 09 '22 06:11

Geert van Horrik