简体   繁体   中英

Throw CollectionChanged of ObservableCollection when nested Property changes

how to notify a ObservableCollection<Book> when a Nested Element changes and i need to know it ?

Perhaps a " ObservableCollection<Book> " and " Book " has a Member " Chapter ". And "Chapter" has a String Property called " Name " and i change the name value. How to throw CollectionChanged of ObservableCollection when Property "Name" in Name->Chapter -> Book -> ObservableCollection<Book> changed ??

Is the common way in MVVM to tunnel it through manuell so that CollectionChanged is fired when PropertyChange is fired ??

Thanks :)


UPDATE: I found a solution in this post: ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

-> Use Binding List or kind of a TrulyObservableCollection from the post bescause ObservableCollection doesn't relay on item notifications like i already mentioned! difference between ObservableCollection and BindingList

-> If u use BindingList remember the disadvantage of this post http://www.themissingdocs.net/wordpress/?p=465


I've had a similar issue in the past. It was caused by my use of Nested Properties and my lack of Notification Propagation.

I solved it by subscribing to the PropertyChanged event each time my object changed. This way I could update my collection when a Nested Property updated.

Make sure that each simple type (eg your Name property) implements OnPropertyChanged, and then each complex type (eg your Book and Chapter properties) implements the Notification Propagation.

Your Observable Collection should update accordingly.

Example:

private Book _book;

public Book Book
    {
        get
        {
            return _book;
        }
        set
        {
            if (value == _book|| value == null)
                return;

            if (_book!= null)
                _book.PropertyChanged -= BookPropertyChanged;

            _book= value;
            _book.PropertyChanged += BookPropertyChanged;

            UpdateProperties();
        }
    }

Update Methods:

private void BookPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        OnPropertyChanged(string.Empty);
    }

public void UpdateProperties()
    {
        OnPropertyChanged(string.Empty);
    }

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM