Search code examples
wpfeventstry-catchobservablecollectionpropertychanged

WPF Catch ObservableCollection's item property changes


Hi I was trying a few ways of doing this but either wasn't successful or it wasn't ideal. I simply want to catch the PropertyChanged event of any item in the collection. I have wired it up manually at the moment but am wondering if there is a more elegant solution:

public class Item : INotifyPropertyChanged
{
    ...
    public delegate void MyPropertyChangedHandler(object sender, PropertyChangedEventArgs e);
    public event MyPropertyChangedHandler MyPropertyChanged;

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
        PropertyChanged(this, args);
        if (MyPropertyChanged != null) MyPropertyChanged(this, args);
    }
    ...
}

public class ItemCollection : ObservableCollection<Item>
{
    ...
    public delegate void MyPropertyChangedHandler(object sender, PropertyChangedEventArgs e);
    public event MyPropertyChangedHandler MyPropertyChanged;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach (Item item in e.NewItems)
            {
                item.MyPropertyChanged += new Item.MyPropertyChangedHandler(item_MyPropertyChanged);
            }
        }

        base.OnCollectionChanged(e);
    }

    void item_MyPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        MyPropertyChanged(sender, e);
    }
    ...
}

Then I can easily attach to the collection's MyPropertyChanged event and it works well but more elegant anyone?

Thanks in advance


Solution

  • you are pretty much doing what you need to do, AFIK there is no better way to do this.

    one thing, you might want to add code to remove your event handler when the item is removed from the collection, to be a good citizen and to avoid memory leaks.