Consuming PropertyChanged events from ObservableCollection

george_yefchak's Avatar

george_yefchak

06 Feb, 2018 05:37 PM

Hi,

I've seen this note "Consuming the INotifyPropertyChanged interface" located here:
 http://doc.postsharp.net/inotifypropertychanged-add#consuming

However, I'm still not able to understand exactly how to implement the solution for this situation:
I have an ObservableCollection<MyType> declared with [AggregateAllChanges]. How can I create a handler to react to changes within the collection's members?

Thanks,
--George

  1. Support Staff 1 Posted by PostSharp Techn... on 07 Feb, 2018 03:31 PM

    PostSharp Technologies's Avatar

    Hello, this is not handled automatically by PostSharp at the moment.

    You need to use a custom collection which processes registration of the event handlers. You can use this one:

    [NotifyPropertyChanged]
    class ObservableCollectionEx<T> : ObservableCollection<T>
    {
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (T item in e.OldItems)
                {
                    ((INotifyPropertyChanged) item).PropertyChanged -= OnItemPropertyChanged;
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (T item in e.NewItems)
                {
                    ((INotifyPropertyChanged) item).PropertyChanged += OnItemPropertyChanged;
                }
            }
    
            base.OnCollectionChanged(e);
        }
    
        protected void OnPropertyChanged(string propertyName)
        {
            base.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    
        protected void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            NotifyPropertyChangedServices.SignalPropertyChanged(this, "Item[]");
    
            NotifyCollectionChangedEventArgs collectionChangedEventArgs =
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
            base.OnCollectionChanged(collectionChangedEventArgs);
        }
    }
    

    Best regards,
    -tony

  2. Support Staff 2 Posted by PostSharp Techn... on 20 Feb, 2018 03:49 PM

    PostSharp Technologies's Avatar

    Hello,

    We are going to close this request as there have not been any further updates. Please feel free to reopen the discussion if you need more help.

    Thanks,
    PostSharp Team

  3. PostSharp Technologies closed this discussion on 20 Feb, 2018 03:49 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac