Subscribe to INotifyPropertyChanged for nested (child) objects

后端 未结 6 1273
执念已碎
执念已碎 2020-12-04 22:05

I\'m looking for a clean and elegant solution to handle the INotifyPropertyChanged event of nested (child) objects. Example code:

<         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 22:51

    I think what you're looking for is something like WPF binding.

    How INotifyPropertyChanged works is that the RaisePropertyChanged("BestFriend"); must only be fored when the property BestFriend changes. Not when anything on the object itself changes.

    How you would implement this is by a two step INotifyPropertyChanged event handler. Your listener would register on the changed event of the Person. When the BestFriend gets set/changed, you register on the changed event of the BestFriend Person. Then, you start listening on changed events of that object.

    This is exactly how WPF binding implements this. The listening to changes of nested objects is done through that system.

    The reason this is not going to work when you implement it in Person is that the levels can become very deep and the changed event of BestFriend does not mean anything anymore ("what has changed?"). This problem gets larger when you have circular relations where e.g. the best friend of your monther is the mother of your best fiend. Then, when one of the properties change, you get a stack overflow.

    So, how you would solve this is to create a class with which you can build listeners. You would for example build a listener on BestFriend.FirstName. That class would then put an event handler on the changed event of Person and listen to changes on BestFriend. Then, when that changes, it puts a listener on BestFriend and listens for changes of FirstName. Then, when that changes, it sends raises an event and you can then listen to that. That's basically how WPF binding works.

    See http://msdn.microsoft.com/en-us/library/ms750413.aspx for more information on WPF binding.

提交回复
热议问题