Gis*_*shu 34 c# collections .net-3.5
正在考虑System.Collections.ObjectModel ObservableCollection<T>上课.这个很奇怪,因为
我需要的是将一批对象添加到集合中,并且侦听器还将批处理作为通知的一部分.我错过了ObservableCollection的东西吗?还有其他课程符合我的规范吗?
更新:尽量不要自己动手.我必须建立添加/删除/更改等等.很多东西.
相关问:https:
//stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each
fry*_*bob 19
似乎INotifyCollectionChanged界面允许在添加多个项目时进行更新,所以我不确定为什么ObservableCollection<T>没有AddRange.您可以为其创建扩展方法AddRange,但这会导致添加的每个项目都发生事件.如果这是不可接受的,您应该能够继承ObservableCollection<T>如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
那个想法和fryguybob的想法一样 - 有点奇怪,ObservableCollection有点半完成了.这件事的事件args甚至没有使用Generics ..让我使用IList(就是这样......昨天:)经过测试的Snippet跟随......
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace MyNamespace
{
public class ObservableCollectionWithBatchUpdates<T> : ObservableCollection<T>
{
public void AddRange(ICollection<T> obNewItems)
{
IList<T> obAddedItems = new List<T>();
foreach (T obItem in obNewItems)
{
Items.Add(obItem);
obAddedItems.Add(obItem);
}
NotifyCollectionChangedEventArgs obEvtArgs = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
obAddedItems as System.Collections.IList);
base.OnCollectionChanged(obEvtArgs);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19204 次 |
| 最近记录: |