本文介绍了实施CollectionChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经加入 Col​​lectionChanged事件处理(onCollectionChanged)的ObservableCollection 属性之一。

I have added CollectionChanged eventhandler(onCollectionChanged) to one of the ObservableCollection property.

我已经发现了 onCollectionChanged 方法被调用只有在添加项目或删除项目到集合的情况下,而不是在集合项目的情况下被编辑。

I have found out that onCollectionChanged method gets invoked only in case of add items or remove items to the collection, but not in the case of collection item gets edited.

我想知道如何发送新添加,删除和编辑的项目列表/集合在一个单一的集合。

I would like to know how to send the list/collection of newly added, removed and edited items in a single collection.

感谢。

推荐答案

您有一个的PropertyChanged 监听器添加到每个项目(必须实现 INotifyPropertyChanged的),以获取有关观察的列表编辑对象的通知。

You have to add a PropertyChanged listener to each item (which must implement INotifyPropertyChanged) to get notification about editing objects in a observable list.

public ObservableCollection<Item> Names { get; set; }
public List<Item> ModifiedItems { get; set; }

public ViewModel()
{
   this.ModifiedItems = new List<Item>();

   this.Names = new ObservableCollection<Item>();
   this.Names.CollectionChanged += this.OnCollectionChanged;
}

void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null)
    {
        foreach(Item newItem in e.NewItems)
        {
            ModifiedItems.Add(newItem);

            //Add listener for each item on PropertyChanged event
            newItem.PropertyChanged += this.OnItemPropertyChanged;
        }
    }

    if (e.OldItems != null)
    {
        foreach(Item oldItem in e.OldItems)
        {
            ModifiedItems.Add(oldItem);

            oldItem.PropertyChanged -= this.OnItemPropertyChanged;
        }
    }
}

void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    Item item = sender as Item;
    if(item != null)
       ModifiedItems.Add(item);
}

也许你得检查一些项目已经在ModifedItems-名单(名单的方法包含(obj对象)),且仅当此方法的结果就是虚假添加新项目

项目必须实施 INotifyPropertyChanged的。看到这个来知道怎么办。正如罗伯特Rossney说你也可以与 IEditableObject - 如果你有要求

The class Item must implement INotifyPropertyChanged. See this example to know how. As Robert Rossney said you can also make that with IEditableObject - if you have that requirement.

这篇关于实施CollectionChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:22