开发者

How Binding internally works? Is IObserver more optimized than traditional INotifyPropertyChanged?

I used INotifyPropertyChanged for the first time in a simple WPF application. I want to know how exactly Binding internally works. Is it the CLR which checks for any class with INotifyPropertyChanged implementation and records the开发者_JS百科 subscribers that need to be informed about the changes?

While I tried this on .NET 3.5, I read about IObserver available with .NET 4.0. Is IObserver more optimized than the traditional INotifyPropertyChanged way?


INotifyPropertyChanged is just an interface that a class can implement. It is up to the implementors to determine how to handle the actual changes.

In the case of WPF, when a one way Binding is created, the binding object verifies if the object implements INotifyPropertyChanged. If it does, it attaches an event handler. It might be a weak reference event handler, because of memory leak concerns, but let's skip that detail for now. When the PropertyChanged event is changed, the Binding object verifies that the Path it has is the same as the PropertyName coming from the event. If yes, the binding fetches the value and sends it over to the target over the Dispatcher. The CLR itself doesn't care what the event is; its just a matter of subscribing to the PropertyChanged event via standard .Net events. An important point is that the INotifyPropertyChanged, like the name implies, is specific eventing to indicate that an object's property value has changed.

The IObserver interface is meant for generic notifications. These notifications can, I guess, be property notifications but it is meant to be a very generic interface.

As to optimizations, it all depends on the implementation, not the interface itself.


The WPF binding system looks for the INotifyPropertyChanged interface, not the CLR. The WPF binding engine has lots of moving parts, but you can assume that the BindingExpression is the one that ultimately subscribes to the PropertyChanged event.

The IObserver interface serves a different function than INotifyPropertyChanged. The latter is used to indicate when a property's value has changed (a very specific task), the former is used to define a generic/reusable observer design pattern.

I don't believe the WPF binding system supports IObserver and I doubt it would anytime soon.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜