How to implement a property changed notification without making an explicit call?

独自空忆成欢 提交于 2019-12-24 13:56:56

问题


In WPF there is the concept of two-way data binding, where when an object property value is updated in the db, it the framework also updates the view when the INotifyPropertyChanged interface is implemented.

I'm looking for something like this functionality in C# but not using WPF.

The scenario is that when an object property is updated, a series of notifications are sent to the other consumers of this object, notifying them of the property change.

So the flow is:

  1. Update the database
  2. Notify consumer 1
  3. Notify consumer 2

This process requires three separate lines. Is there a way to implement the WPF concept of a property changed to update whoever the consumers are (say, event-driven) without needing to explicitly notify the consumers?


回答1:


When implementing INotifyPropertyChanged, you are simply raising an event whenever you want to let consumers know that the property has changed. You only make one call to raise the event regardless of how many consumers are listening to that event.

If what you're trying to achieve is reduce boilerplate code, i.e. have only one line of code per setter, you can have a look at this simple solution, which can be made even nicer with C# 5.



来源:https://stackoverflow.com/questions/16619790/how-to-implement-a-property-changed-notification-without-making-an-explicit-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!