有效地将一系列值添加到 ObservableCollection

发布于 2024-12-22 10:23:26 字数 532 浏览 3 评论 0原文

我有一个 ObservableCollection 项目,它绑定到我视图中的列表控件。

我遇到一种情况,我需要将一大块值添加到集合的开头。 Collection.Insert 文档将每个插入指定为 O(n) 操作,并且每个插入还会生成一个 CollectionChanged 通知。

因此,理想情况下,我希望一次性插入整个项目范围,这意味着只需对基础列表进行一次洗牌,并希望有一个 CollectionChanged 通知(大概是“重置”)。

Collection 不会公开任何执行此操作的方法。 ListInsertRange(),但 IListCollection 通过以下方式公开它的 Items 属性没有。

有什么办法可以做到这一点吗?

I have an ObservableCollection of items that is bound to a list control in my view.

I have a situation where I need to add a chunk of values to the start of the collection.
Collection<T>.Insert documentation specifies each insert as an O(n) operation, and each insert also generates a CollectionChanged notification.

Therefore I would ideally like to insert the whole range of items in one move, meaning only one shuffle of the underlying list, and hopefully one CollectionChanged notification (presumably a "reset").

Collection<T> does not expose any method for doing this. List<T> has InsertRange(), but IList<T>, that Collection<T> exposes via its Items property does not.

Is there any way at all to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

混浊又暗下来 2024-12-29 10:23:26

ObservableCollection 公开一个受保护的 Items 属性,它是没有通知语义的基础集合。这意味着您可以通过继承 ObservableCollection 来构建一个执行您想要的操作的集合:

class RangeEnabledObservableCollection<T> : ObservableCollection<T>
{
    public void InsertRange(IEnumerable<T> items) 
    {
        this.CheckReentrancy();
        foreach(var item in items)
            this.Items.Add(item);
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

用法:

void Main()
{
    var collection = new RangeEnabledObservableCollection<int>();
    collection.CollectionChanged += (s,e) => Console.WriteLine("Collection changed");
    collection.InsertRange(Enumerable.Range(0,100));
    Console.WriteLine("Collection contains {0} items.", collection.Count);  
}

The ObservableCollection exposes an protected Items property which is the underlying collection without the notification semantics. This means you can build a collection that does what you want by inheriting ObservableCollection:

class RangeEnabledObservableCollection<T> : ObservableCollection<T>
{
    public void InsertRange(IEnumerable<T> items) 
    {
        this.CheckReentrancy();
        foreach(var item in items)
            this.Items.Add(item);
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

Usage:

void Main()
{
    var collection = new RangeEnabledObservableCollection<int>();
    collection.CollectionChanged += (s,e) => Console.WriteLine("Collection changed");
    collection.InsertRange(Enumerable.Range(0,100));
    Console.WriteLine("Collection contains {0} items.", collection.Count);  
}
人心善变 2024-12-29 10:23:26

为了使上述答案有用而无需使用反射派生新的基类,下面是一个示例:

public static void InsertRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
{
  var enumerable = items as List<T> ?? items.ToList();
  if (collection == null || items == null || !enumerable.Any())
  {
    return;
  }

  Type type = collection.GetType();

  type.InvokeMember("CheckReentrancy", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, collection, null);
  var itemsProp = type.BaseType.GetProperty("Items", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
  var privateItems = itemsProp.GetValue(collection) as IList<T>;
  foreach (var item in enumerable)
  {
    privateItems.Add(item);
  }

  type.InvokeMember("OnPropertyChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null,
    collection, new object[] { new PropertyChangedEventArgs("Count") });

  type.InvokeMember("OnPropertyChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null,
    collection, new object[] { new PropertyChangedEventArgs("Item[]") });

  type.InvokeMember("OnCollectionChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, 
    collection, new object[]{ new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)});
}

To make the above answer useful w/o deriving a new base class using reflection, here's an example:

public static void InsertRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
{
  var enumerable = items as List<T> ?? items.ToList();
  if (collection == null || items == null || !enumerable.Any())
  {
    return;
  }

  Type type = collection.GetType();

  type.InvokeMember("CheckReentrancy", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, collection, null);
  var itemsProp = type.BaseType.GetProperty("Items", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
  var privateItems = itemsProp.GetValue(collection) as IList<T>;
  foreach (var item in enumerable)
  {
    privateItems.Add(item);
  }

  type.InvokeMember("OnPropertyChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null,
    collection, new object[] { new PropertyChangedEventArgs("Count") });

  type.InvokeMember("OnPropertyChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null,
    collection, new object[] { new PropertyChangedEventArgs("Item[]") });

  type.InvokeMember("OnCollectionChanged", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, 
    collection, new object[]{ new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)});
}
感受沵的脚步 2024-12-29 10:23:26

这个答案没有向我显示DataGrid中的新条目。这个 OnCollectionChanged 对我有用:

public class SilentObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> enumerable)
    {
        CheckReentrancy();

        int startIndex = Count;

        foreach (var item in enumerable)
            Items.Add(item);

        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(enumerable), startIndex));
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
    }
}

This answer didn't show me the new entries in a DataGrid. This OnCollectionChanged works for me:

public class SilentObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> enumerable)
    {
        CheckReentrancy();

        int startIndex = Count;

        foreach (var item in enumerable)
            Items.Add(item);

        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List<T>(enumerable), startIndex));
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
    }
}
迷迭香的记忆 2024-12-29 10:23:26

10 年后,现在我必须在项目中使用 C#,并且我不希望触发多个 OnCollectionChanged。我已将 @outbred 的答案修改为扩展类。

用法:

var stuff = new ObservableCollection<Stuff>() {...};
...
// will trigger only 1 OnCollectionChanged event
stuff.ReplaceCollection(newThings);

// equivalent without the extension methods
// stuff.Clear();       // triggers 1 OnCollectionChanged 
// foreach (var thing in newThings)
//    stuff.Add(thing); // triggers multiple OnCollectionChanged

ObservableCollectionExtensions.cs

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace System.Collections.ObjectModel
{
    public static class ObservableCollectionExtensions
    {
        private static BindingFlags ProtectedMember = BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic;
        private static BindingFlags ProtectedProperty = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic;

        /// <summary>
        /// Insert a collection without triggering OnCollectionChanged event 
        /// </summary>
        private static void InsertWithoutNotify<T>(this ObservableCollection<T> collection, IEnumerable<T> items, int index = -1)
        {
            if (collection == null || items == null || !items.Any()) return;
            Type type = collection.GetType();

            type.InvokeMember("CheckReentrancy", ProtectedMember, null, collection, null);

            PropertyInfo itemsProp = type.BaseType.GetProperty("Items", ProtectedProperty);
            IList<T> protectedItems = itemsProp.GetValue(collection) as IList<T>;

            // Behave the same as Add if no index is being passed
            int start = index > -1 ? index : protectedItems.Count();
            int end = items.Count();
            for (int i = 0; i < end; i++)
            {
                protectedItems.Insert(start + i, items.ElementAt(i));
            }

            type.InvokeMember("OnPropertyChanged", ProtectedMember, null,
              collection, new object[] { new PropertyChangedEventArgs("Count") });

            type.InvokeMember("OnPropertyChanged", ProtectedMember, null,
              collection, new object[] { new PropertyChangedEventArgs("Item[]") });
        }

        public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            InsertWithoutNotify(collection, items);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
              collection, new object[] {
                  // Notify that we've added new items into the collection
                  new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
              });
        }

        public static void InsertRange<T>(this ObservableCollection<T> collection, int index, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            InsertWithoutNotify(collection, items, index);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
              collection, new object[] {
                  // Notify that we've added new items into the collection
                  new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
              });
        }

        public static void ReplaceCollection<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            // Clear the underlaying list items without triggering a change
            PropertyInfo itemsProp = type.BaseType.GetProperty("Items", ProtectedProperty);
            IList<T> protectedItems = itemsProp.GetValue(collection) as IList<T>;
            protectedItems.Clear();

            // Perform the actual update
            InsertWithoutNotify(collection, items);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
                collection, new object[] {
                    // Notify that we have replaced the entire collection
                    new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
                });
        }
    }
}

10 years later, now that I've to use C# in my project and I don't wish to trigger multiple OnCollectionChanged. I've revised @outbred's answer into an Extension class.

Usage:

var stuff = new ObservableCollection<Stuff>() {...};
...
// will trigger only 1 OnCollectionChanged event
stuff.ReplaceCollection(newThings);

// equivalent without the extension methods
// stuff.Clear();       // triggers 1 OnCollectionChanged 
// foreach (var thing in newThings)
//    stuff.Add(thing); // triggers multiple OnCollectionChanged

The ObservableCollectionExtensions.cs:

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace System.Collections.ObjectModel
{
    public static class ObservableCollectionExtensions
    {
        private static BindingFlags ProtectedMember = BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic;
        private static BindingFlags ProtectedProperty = BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic;

        /// <summary>
        /// Insert a collection without triggering OnCollectionChanged event 
        /// </summary>
        private static void InsertWithoutNotify<T>(this ObservableCollection<T> collection, IEnumerable<T> items, int index = -1)
        {
            if (collection == null || items == null || !items.Any()) return;
            Type type = collection.GetType();

            type.InvokeMember("CheckReentrancy", ProtectedMember, null, collection, null);

            PropertyInfo itemsProp = type.BaseType.GetProperty("Items", ProtectedProperty);
            IList<T> protectedItems = itemsProp.GetValue(collection) as IList<T>;

            // Behave the same as Add if no index is being passed
            int start = index > -1 ? index : protectedItems.Count();
            int end = items.Count();
            for (int i = 0; i < end; i++)
            {
                protectedItems.Insert(start + i, items.ElementAt(i));
            }

            type.InvokeMember("OnPropertyChanged", ProtectedMember, null,
              collection, new object[] { new PropertyChangedEventArgs("Count") });

            type.InvokeMember("OnPropertyChanged", ProtectedMember, null,
              collection, new object[] { new PropertyChangedEventArgs("Item[]") });
        }

        public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            InsertWithoutNotify(collection, items);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
              collection, new object[] {
                  // Notify that we've added new items into the collection
                  new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
              });
        }

        public static void InsertRange<T>(this ObservableCollection<T> collection, int index, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            InsertWithoutNotify(collection, items, index);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
              collection, new object[] {
                  // Notify that we've added new items into the collection
                  new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
              });
        }

        public static void ReplaceCollection<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            if (collection == null || items == null || !items.Any()) return;

            Type type = collection.GetType();

            // Clear the underlaying list items without triggering a change
            PropertyInfo itemsProp = type.BaseType.GetProperty("Items", ProtectedProperty);
            IList<T> protectedItems = itemsProp.GetValue(collection) as IList<T>;
            protectedItems.Clear();

            // Perform the actual update
            InsertWithoutNotify(collection, items);

            type.InvokeMember("OnCollectionChanged", ProtectedMember, null,
                collection, new object[] {
                    // Notify that we have replaced the entire collection
                    new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)
                });
        }
    }
}

眼波传意 2024-12-29 10:23:26

例子:
所需步数 0,10,20,30,40,50,60,70,80,90,100
-->最小值=0,最大值=100,步数=11

    static int min = 0;
    static int max = 100;
    static int steps = 11; 

    private ObservableCollection<string> restartDelayTimeList = new ObservableCollection<string> (
        Enumerable.Range(0, steps).Select(l1 => (min + (max - min) * ((double)l1 / (steps - 1))).ToString())
    );

Example:
Desired steps 0,10,20,30,40,50,60,70,80,90,100
--> min=0, max=100, steps=11

    static int min = 0;
    static int max = 100;
    static int steps = 11; 

    private ObservableCollection<string> restartDelayTimeList = new ObservableCollection<string> (
        Enumerable.Range(0, steps).Select(l1 => (min + (max - min) * ((double)l1 / (steps - 1))).ToString())
    );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文