我应该始终在模型中实现INotifyPropertyChanged接口吗? [英] Should I always implement INotifyPropertyChanged interface in model?

查看:76
本文介绍了我应该始终在模型中实现INotifyPropertyChanged接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个模型,该模型几乎是一个只读集合,并且在用户选择一行的网格上显示.

If I have a model which is pretty much a readonly collection and dispayed on a grid, where the user selects a row.

我是否需要始终在模型上实现INotifyPropertyChanged?实施与不实施相比有性能上的好处吗?

Do I need to have INotifyPropertyChanged always implemented on the model? Is there a performance benefit of implementing vs not?

我想知道性能是否受尝试使用

I would like to know if performance is impacted by UI trying to use something like

var x =模型为INotifyPropertyChanged;

var x = Model as INotifyPropertyChanged;

否则就不会使用.

推荐答案

如果在任何数据绑定中使用该模型,则可以,即使完全不可变,也应该实现 INotifyPropertyChanged .原因与性能无关,而是避免内存泄漏.

If you are using the model in any data bindings, then yes, you should implement INotifyPropertyChanged even if it is completely immutable. The reason has nothing to do with performance, but to avoid a memory leak.

Binding 将始终尝试注册更改通知,并且如果您未实现 INotifyPropertyChanged 或公开形式为 [Property] Changed的离散更改事件,它将通过 PropertyDescriptor API注册.默认的基于反射的 PropertyDescriptor 实现使用全局订阅表,并且如果由于某些原因 Binding 不能干净地取消订阅,则视图模型将无限期地保持活动状态.这与绑定订阅 INotifyPropertyChanged 通知时使用的弱事件模式相反.运行时的绑定通常会自行清除,但是Xaml设计器在这种情况下会因泄漏而臭名昭著,这会导致设计器进程的内存消耗在您工作时稳定增长.

A Binding will always try to register for change notifications, and if you do not implement INotifyPropertyChanged or expose discrete change events of the form [Property]Changed, it will register through the PropertyDescriptor API. The default, reflection-based PropertyDescriptor implementation uses a global subscription table, and if for some reason the Binding does not unsubscribe cleanly, your view model will be kept alive indefinitely. This is in contrast to the weak event pattern used when bindings subscribe to INotifyPropertyChanged notifications. Bindings at runtime generally clean up after themselves, but the Xaml designer is notorious for leaking under these circumstances, causing your designer process's memory consumption to rise steadily as you work.

这篇关于我应该始终在模型中实现INotifyPropertyChanged接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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