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

前端 未结 18 2905
一生所求
一生所求 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:03

    Here is a drop-in class that sub-classes ObservableCollection and actually raises a Reset action when a property on a list item changes. It enforces all items to implement INotifyPropertyChanged.

    The benefit here is that you can data bind to this class and all of your bindings will update with changes to your item properties.

    public sealed class TrulyObservableCollection : ObservableCollection
        where T : INotifyPropertyChanged
    {
        public TrulyObservableCollection()
        {
            CollectionChanged += FullObservableCollectionCollectionChanged;
        }
    
        public TrulyObservableCollection(IEnumerable pItems) : this()
        {
            foreach (var item in pItems)
            {
                this.Add(item);
            }
        }
    
        private void FullObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (Object item in e.NewItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
                }
            }
            if (e.OldItems != null)
            {
                foreach (Object item in e.OldItems)
                {
                    ((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
                }
            }
        }
    
        private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {            
            NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
            OnCollectionChanged(args);
        }
    }
    

提交回复
热议问题