实现 CollectionChanged [英] Implementing CollectionChanged

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

问题描述

我已将 CollectionChanged eventhandler(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-List 中(使用 List 的方法 Contains(object obj)),并且仅在该方法的结果为 false 时才添加新项目强>.

Item 类必须实现 INotifyPropertyChanged.请参阅此示例,了解如何操作.正如罗伯特·罗斯尼所说,您也可以使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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