Subscribe to INotifyPropertyChanged for nested (child) objects

后端 未结 6 1264
执念已碎
执念已碎 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条回答
  •  失恋的感觉
    2020-12-04 22:50

    since I wasn't able to find a ready-to-use solution, I've done a custom implementation based on Pieters (and Marks) suggestions (thanks!).

    Using the classes, you will be notified about any change in a deep object tree, this works for any INotifyPropertyChanged implementing Types and INotifyCollectionChanged* implementing collections (Obviously, I'm using the ObservableCollection for that).

    I hope this turned out to be a quite clean and elegant solution, it's not fully tested though and there is room for enhancements. It's pretty easy to use, just create an instance of ChangeListener using it's static Create method and passing your INotifyPropertyChanged:

    var listener = ChangeListener.Create(myViewModel);
    listener.PropertyChanged += 
        new PropertyChangedEventHandler(listener_PropertyChanged);
    

    the PropertyChangedEventArgs provide a PropertyName which will be always the full "path" of your Objects. For example, if you change your Persons's "BestFriend" Name, the PropertyName will be "BestFriend.Name", if the BestFriend has a collection of Children and you change it's Age, the value will be "BestFriend.Children[].Age" and so on. Don't forget to Dispose when your object is destroyed, then it will (hopefully) completely unsubscribe from all event listeners.

    It compiles in .NET (Tested in 4) and Silverlight (Tested in 4). Because the code in seperated in three classes, I've posted the code to gist 705450 where you can grab it all: https://gist.github.com/705450 **

    *) One reason that the code is working is that the ObservableCollection also implements INotifyPropertyChanged, else it wouldn't work as desired, this is a known caveat

    **) Use for free, released under MIT License

提交回复
热议问题