如何检测如果在我的ObservableCollection一个项已改变 [英] How to detect if an item in my ObservableCollection has changed

查看:1463
本文介绍了如何检测如果在我的ObservableCollection一个项已改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这势必的ObservableCollection℃的数据网格;产品> 。当电网更新这个自动更新我的集合中的产品对象。

I have a datagrid which is bound to ObservableCollection<Product>. When the grid is updated this automatically updates the Product object in my collection.

我想现在做的是有某种甚至被触发时,任何对象该集合 - 或 - 某种形式的结合,将回报如有产品已经更新真/假depedant收集更新。

What I want to do now is to have some sort of even that is triggered when any object in the collection is updated -or- some sort of binding to the collection that will return true/false depedant on if any Product has been updated.

的总体目标是有保存,如果没有修改过到我的收藏,如果已经作了修改启用已禁用我的主窗口上的按钮。

The overall objective is to have a save button on my main window that is disabled if no changes have been made to my collection and enabled if changes have been made.

我已经读入 INotifyPropertyChange ,但我不知道怎样才能用它来监视整个集合改变。

I have read into INotifyPropertyChange but I dont see how I can use this to monitor changes on a whole collection.

此外,如果我实现这个接口我的产品类别我没有看到我的UI如何监视集合中的每一个产品 - 或者可以了。

Additionally, if I implement this interface on my Product class I dont see how my UI can monitor every product in the collection - or can it?

推荐答案


  • 实施 INotifyPropertyChanged的产品类与每个属性通知。

  • 在您的视图模型实施 INotifyPropertyChanged的

  • 添加属性 IsDirty 您视图模型(通过通知 INotifyPropertyChanged的

  • 在您的视图模型,订阅 CollectionChanged

  • 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;
    }
    


  • 现在可以绑定到 IsDirty 您的视图模型的属性,例如,可以 Button.IsEnabled 属性绑定直接到它。

  • Now you can bind to IsDirty property of your viewmodel, for example, you can bind Button.IsEnabled property directly to it.

    这篇关于如何检测如果在我的ObservableCollection一个项已改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆