完成View和ViewModel后,如何删除事件处理程序,而不是模型 [英] How do I remove event handlers when I'm finished with a View and ViewModel, but not the Model

查看:98
本文介绍了完成View和ViewModel后,如何删除事件处理程序,而不是模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我经常创建新的Views和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.

因此,可以有多个ViewModel对于给定的模型对象,他们需要从其他地方更改更新。 (我在我的模型上使用 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?
}

我的理解是,事件处理程序将导致模型保留引用到ViewModel,并避免收集垃圾。

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)这是正确的吗?如何判断这些引用是否仍然存在?

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

2)如何确定ViewModel不再需要并取消订阅事件?

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;
    }
}

但是我发现这个美丽的矿块。因此,至少有两个可能的解决方案:(a)实现 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 Pattern 等...

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

这篇关于完成View和ViewModel后,如何删除事件处理程序,而不是模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆