问题
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:
- Update the database
- Notify consumer 1
- 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