How to detect if an item in my ObservableCollection has changed

岁酱吖の 提交于 2019-12-03 01:31:00
  • Implement INotifyPropertyChanged in your Product class with notification for every property.
  • Implement INotifyPropertyChanged in your viewmodel.
  • Add property IsDirty to your ViewModel (with notification through INotifyPropertyChanged.
  • In your viewmodel, subscribe to CollectionChanged

    public YourViewModel()
    {
        ...
        YourCollection.CollectionChanged += YourCollection_CollectionChanged; 
        ...
    }
    
    private void YourCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
    {
        if (args.OldItems != null)
            foreach(var oldItem in args.OldItems)
                oldItem.PropertyChanged -= YourItem_PropertyChanged;
    
        if (args.NewItems != null)
            foreach(var newItem in args.NewItems)
                newItem.PropertyChanged += YourItem_PropertyChanged;
    }
    
    private void Youritem_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs args)
    {
        IsDirty = true;
    }
    
  • Now you can bind to IsDirty property of your viewmodel, for example, you can bind Button.IsEnabled property directly to it.

Just use the ObservableCollection. It has an event called CollectionChanged. If you register it, you can do what you want. Example:

ObservableCollection<string> strings = new ObservableCollection<string>();
strings.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(changed);
strings.Add("Hello");
strings[0] = "HelloHello";

And:

private void changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args)
{
    //You get notified here two times.
}
Manish Basantani

The logic needs to go in your Model (Product class). A clean approach would be to expose IsDirty property (backed by field) in your model.

And your ViewModel would have a Command binding with CanSave checking the internal collection, and return true if Any of the item in collection IsDirty=true.

Orkun Ozen

I think subscribing to the PropertyChanged event for each of the objects in your collection and firing this event, for example, in the setter of your objects can work.

However, I think you don't need to do all this to figure out if a cell is changed in your grid. I think you can do something like what they do here instead:

http://social.msdn.microsoft.com/Forums/en/wpf/thread/81131225-90fb-40f9-a311-066952c7bc43

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!