它的.Net集合添加多个对象一次得到通知? [英] Which .Net collection for adding multiple objects at once and getting notified?

查看:110
本文介绍了它的.Net集合添加多个对象一次得到通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正考虑在 System.Collections.ObjectModel的ObservableCollection< T> 类。这一次很奇怪,因为

Was considering the System.Collections.ObjectModel ObservableCollection<T> class. This one is strange because

  • 在它有一个添加方法,需要一个项只。没有的AddRange或同等学历。
  • 的通知事件参数有NewItems属性,它是一个的IList (对象..不是T)
  • it has an Add Method which takes one item only. No AddRange or equivalent.
  • the Notification event arguments has a NewItems property, which is a IList (of objects.. not T)

在这里,我需要的是一批对象添加到集合与听者也得到了一批作为通知的一部分。我缺少的东西的ObservableCollection?是否有另一个类,以满足我的规格?

My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?

更新:不要想推出自己的,只要是可行的。我必须建立在添加/删除/修改等一大堆东西。


相关问:
<一href="http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">http://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each

推荐答案

看来, INotifyCollectionChanged 接口允许在添加多个项目的更新,所以我不知道为什么的ObservableCollection&LT; T&GT; 不具有的AddRange 。你可以做的的AddRange 的扩展方法,但是这将导致事件被添加每一个项目。如果这是不能接受的,你应该能够从继承的ObservableCollection&LT; T&GT; 如下:

It seems that the INotifyCollectionChanged interface allows for updating when multiple items were added, so I'm not sure why ObservableCollection<T> doesn't have an AddRange. You could make an extension method for AddRange, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from ObservableCollection<T> as follows:

public class MyObservableCollection<T> : ObservableCollection<T>
{
    // matching constructors ...

    bool isInAddRange = false;

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        // intercept this when it gets called inside the AddRange method.
        if (!isInAddRange) 
            base.OnCollectionChanged(e);
    }


    public void AddRange(IEnumerable<T> items)
    {
         isInAddRange = true;
         foreach (T item in items)
            Add(item);
         isInAddRange = false;

         var e = new NotifyCollectionChangedEventArgs(
             NotifyCollectionChangedAction.Add,
             items.ToList());
         base.OnCollectionChanged(e);
    }
}

这篇关于它的.Net集合添加多个对象一次得到通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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