Is INotifyPropertyChanged only for the presentation layer?
The INotifyPropertyChanged is obviously very useful in the view model for data binding to the view. Should I also use this interface in other parts of my application (e.g. in the business layer) when I want notifications of property changes, or I am better off using other notification mechanisms? I 开发者_如何学编程realize that there is nothing stopping me from using it, but are there any reasons that I shouldn't?
INotifyPropertyChanged
is not very explicit and it is error prone, since you somehow need to specify by string the property that changed, potentially becoming stale information when you refactor said property to a different name. If it is your class that consumes some notification I think it makes a lot more sense to be more explicit about it and state what changes.
INotifyPropertyChanged can be a bit of a pain to implement, though there are tools that can make it cleaner and less error-prone (for example, PostSharp can automate the plumbing of the setter notifiers so you don't have to code them manually (no more string references in the setter) and tools like Resharper can perform renames that also update string references to the property name.)
I personally do implement this interface in my Model layer, though it doesn't get consumed nearly as much by other Model objects. Most of the time my Model objects aren't usually listening for a single property change; rather, they're watching for an overall state change that may involve several properties. This kind of change is better notified with a specific event. I do, however, find myself using INotifyCollectionChanged quite a bit, exposing collections of objects in public ObservableCollection classes and responding to change events rather than creating a bunch of wrapper methods to access a private collection and update state.
精彩评论