如何拦截NotifyPropertyChange事件
我最近刚刚发现了一个 INotifyPropertyChange 接口。我设法在我的类中实现这个接口,一切正常。但是我想知道是否可以在代码中拦截此事件并触发函数 假设我有一个函数
DoStuff()
,并且我不想在每次 property1、property2 或 property3 更改时触发该函数。 当然,我可以将此函数放在我的类中的 set 块中,但这不是一个好主意(我认为)。
I just recently discovered an INotifyPropertyChange interface. I managed to implement this interface in my clss and everything works fine. However I was wondering if it is possible to intercept this event in code and fire a function
Let's say that I have a function
DoStuff()
and I wan't to fire this function everytime property1, property2 or property3 changes.
Of course I could put this function in set block in my class but this is not a good idea(I think).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您是否需要它来替换现有的 NotifyPropertyChanged 事件处理程序,或者只是在调用 NotifyPropertyChanged 时调用它?
如果您指的是第二个,您可以简单地注册一个事件处理程序
edit
您可以添加一个在 NotifyPropertyChanged 上调用的事件处理程序,检查属性参数是否等于 Property1、Property2 或 Property3,并且仅然后将其转发到您要调用的实际函数。
Did you need it to replace the existing NotifyPropertyChanged event handlers, or just get called when NotifyPropertyChanged is called?
If you mean the second, you can simply register an event handler
edit
You can add an event handler that gets called on NotifyPropertyChanged, checks if the property parameter is equal to Property1, Property2, or Property3, and only then forwards it to the actual function you want to call.
窃取 Elisha 的答案来回答 Merlyn 的答案中的问题
如果 DoStuff 所在的类是您可以执行的成员,
否则您可以让 otherClass 在您的主代码中自行注册一个事件。
Stealing Elisha's answer to answer your question in Merlyn's answer
If the class DoStuff is in is a member you can do
Otherwise you can just have otherClass register a event on its own in your main code.
您可以从 RaisePropertyChanged() 方法触发该方法:
You could fire the method from a RaisePropertyChanged() method:
拦截 PropertyChanged 事件:
http://msdn.microsoft .com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
Intercept the PropertyChanged Event:
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
如果您的意思是使用内部方法来处理此事件,您可以通过在类构造函数中注册该事件来完成。例如:
如果拦截方法属于其他类:
If you mean to internal method that'll handle this event you can do it by registering to the event in the class constructor. For example:
If the intercepting method belongs to other class: