如何删除事件处理程序,当我完成了一个视图和视图模型,而不是模型视图、模型、当我、而不是

2023-09-04 00:38:43 作者:耀眼旳星光

在我的应用程序,我常常创造新的视图和的ViewModels,但坚持同样的模式。例如,我可能显示的项目的列表的简单视图在我的主窗口中,并且与任何特定项目的进一步细节另一个窗口。在详细信息窗口可以打开和在任何时间关闭,或者多个窗口可以同时打开为列表上不同的项目。

In my application, I am often creating new Views and ViewModels, but persisting the same Models. For example, I might show a simple view of a list of items in my main window, and have another window with further details of any particular item. The detail window can be opened and closed at any time, or multiple windows can be opened simultaneously for different items on the list.

因此​​,可以有一个以上的视图模型对于给定的模型对象,并且他们需要与来自其他地方的变化被更新。 (我使用 INotifyPropertyChanged的在我的模型)。我想摆脱的ViewModels的时候,我做了他们,也就是说,作为细节窗口被关闭。

Therefore, there can be more than one ViewModel for a given model object, and they need to be updated with changes from other places. (I'm using INotifyPropertyChanged on my models.) I want to get rid of ViewModels when I am done with them, i.e., as the detail window is closed.

public DetailViewModel(MyDetailModel detailModel)
{
    // Retain the Detail Model
    this.model = detailModel;

    // Handle changes to the Model not coming from this ViewModel
    this.model.PropertyChanged += model_PropertyChanged;  // Potential leak?
}

这是我的理解是,事件处理程序将导致模型保留提及视图模型,并保持它得到垃圾收集。

It is my understanding that the event handler will cause the Model to retain a reference to the ViewModel, and keep it from getting garbage collected.

1)这是正确的?我怎样才能知道,如果这些引用仍然present?

1) Is this correct? How can I tell if these references are still present?

2)我应该如何确定视图模型不再需要,并从事件退订?

2) How should I determine the ViewModel is no longer needed and unsubscribe from the events?

推荐答案

起初我还以为这将是一段路要走:

At first I thought this would be the way to go:

public class DetailViewModel : IDisposable
{
    public DetailViewModel(MyDetailModel detailModel)
    {
        // Retain the Detail Model
        this.model = detailModel;

        // Handle changes to the Model not coming from this ViewModel
        this.model.PropertyChanged += model_PropertyChanged;  // Potential leak?
    }

    public void Dispose()
    {
        this.model.PropertyChanged -= model_PropertyChanged;
    }
}

但后来我发现这个美丽的金块。所以,至少有两种可能的解决方案:(一)样本实施的IDisposable ,及(b)违反的IDisposable 参数。当我离开的辩论给你。 ;)

But then I found this beautiful nugget. So, there are at least two possible solutions: (a) sample implementing IDisposable, and (b) arguments against IDisposable. I'll leave the debate to you. ;)

您也可以考虑 WeakEvent模式的等等...

You may also consider the WeakEvent Pattern among others ...