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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With