C# - 如何确定属性是否更改
我需要知道公共属性(具有 getter 和 setter)是否已更改。该属性位于一个简单的类中(没有用户控件/组件等)。
有没有一种优雅的方式来订阅某种事件,在属性更改时发出通知?
我试图了解微软在他们的 Binding 对象中做了什么(使用反射器),这引导我探索 PropertyDescriptor.AddValueChanged 方法,但它对我不起作用。也许它仅适用于组件/用户控件...
有什么建议吗?
谢谢,
阿迪巴尔达
I need to know whether a public property (which has getter & setter) is changed. The property is in a simple class (no user control/component etc).
Is there an elegant way to subscribe to some kind of event which notifies when property is changed?
I tried to see what microsoft is doing in their Binding object (using reflector) and that lead me to explore the PropertyDescriptor.AddValueChanged method but it didn't worked for me. maybe it works only for components/user controls...
Any suggestions?
Thanks,
Adi Barda
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需实现 INotifyPropertyChanged 接口即可:
http://msdn.microsoft.com/en-us/library /system.componentmodel.inotifypropertychanged.aspx
这是一个众所周知的接口,由绑定 API 使用。只需按照该 msdn 页面上的示例实现即可。
Just implement the INotifyPropertyChanged interface:
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
This is a pretty well known interface, which is used by the binding APIs. Just follow the example implementation on that msdn page.
INotifyPropertyChanged 应该可以工作,但您也可以创建自己的特定于该属性的事件,而无需拖动到 system.componentmodel 中。
INotifyPropertyChanged should work but you could also just create your own event that is specific to the property without dragging in system.componentmodel.