我们自己的代码是否应该订阅PropertyChanged? [英] Should our own code subscribe to PropertyChanged?

查看:85
本文介绍了我们自己的代码是否应该订阅PropertyChanged?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有许多实现INotifyPropertyChanged的数据对象,以允许WPF绑定更新.在很多地方,我们的代码都订阅了PropertyChanged,因为我们对某些值更新感兴趣.

这导致代码很丑陋,我们需要检查实际上更改了哪个属性(我们使用表达式来执行此操作,因此它始终是类型/重构安全的).

当我们想要订阅某个特定事件(例如PriceChanged等)时,还是要挂接到PropertyChanged并检查属性名称时,是偏好设置的?

解决方案

如果要预订的属性数量不是很大,我将创建专用事件,因为它们在可读性和可发现性方面更好. /p>

但是,如果有很多属性,答案就不是那么明显了.我通常尝试通过应用观察者同步模式来避免这种情况(订阅模型更改而不是ViewModel) .它可以帮助我使虚拟机保持精简状态.

We have a number of data objects that realize INotifyPropertyChanged to allow for WPF Binding updates. There are also a number of places where our code subscribes to PropertyChanged because we're interested in some value updates.

This results in pretty ugly code where we need to check which property actually changed (we do this using Expressions so it's always type/refactor safe).

Is the preference to raise a specific event (PriceChanged etc...) for when we want to subscribe to it, or hook into PropertyChanged and check the property name?

解决方案

If a number of properties you want to subscribe to is not very big, I'd create dedicated events as they are better in terms of readability and discoverability.

However, if there are quite a few properties the answer is not so obvious. I usually try to avoid such situations by applying Observer Synchronization pattern (subscribing to Model changes rather than ViewModel). It helps me keep VMs thin.

这篇关于我们自己的代码是否应该订阅PropertyChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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