简体   繁体   English

使用System.Windows.Interactivity.EventTrigger的ViewModel中的事件是弱引用吗?

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

I have in my ViewModel an event. 我在ViewModel中有一个事件。

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. 在我的视图中,我使用EventTrigger来监听事件以调用一个动作。

 <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. 由于我的View是按需创建的,因此意味着根据用户在Visual树中添加和删除控件。 The source object (ViewModel) has a longer lifetime than the listener (View). 源对象(ViewModel)的生命周期比侦听器(View)长。 Therefore, using the above code, will the event still have a strong reference to the removed listener(View)? 因此,使用上面的代码,事件是否仍然强烈引用已删除的侦听器(View)?

In the OnDetaching of the EventTriggerBase, it calls the following code: 在EventTriggerBase的OnDetaching中,它调用以下代码:

 this.OnSourceChanged(this.Source, null);

This means that the source is being set from Source to null and the event is unsubscribed. 这意味着源从Source设置为null并且事件已取消订阅。 No memory leaks when the view is correctly unloaded which means the Detach method is being called. 正确卸载视图时没有内存泄漏,这意味着正在调用Detach方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM