ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

前端 未结 18 2918
一生所求
一生所求 2020-11-22 02:06

Does anyone know why this code doesn\'t work:

public class CollectionViewModel : ViewModelBase {  
    public ObservableCollection Con         


        
18条回答
  •  无人共我
    2020-11-22 03:12

    You can also use this extension method to easily register a handler for item property change in relevant collections. This method is automatically added to all the collections implementing INotifyCollectionChanged that hold items that implement INotifyPropertyChanged:

    public static class ObservableCollectionEx
    {
        public static void SetOnCollectionItemPropertyChanged(this T _this, PropertyChangedEventHandler handler)
            where T : INotifyCollectionChanged, ICollection 
        {
            _this.CollectionChanged += (sender,e)=> {
                if (e.NewItems != null)
                {
                    foreach (Object item in e.NewItems)
                    {
                        ((INotifyPropertyChanged)item).PropertyChanged += handler;
                    }
                }
                if (e.OldItems != null)
                {
                    foreach (Object item in e.OldItems)
                    {
                        ((INotifyPropertyChanged)item).PropertyChanged -= handler;
                    }
                }
            };
        }
    }
    

    How to use:

    public class Test
    {
        public static void MyExtensionTest()
        {
            ObservableCollection c = new ObservableCollection();
            c.SetOnCollectionItemPropertyChanged((item, e) =>
            {
                 //whatever you want to do on item change
            });
        }
    }
    

提交回复
热议问题