.net中ObservableCollection有什么用?
当前回答
class FooObservableCollection : ObservableCollection<Foo>
{
protected override void InsertItem(int index, Foo item)
{
base.Add(index, Foo);
if (this.CollectionChanged != null)
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
}
}
var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;
collection.Add(new Foo());
void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
Foo newItem = e.NewItems.OfType<Foo>().First();
}
其他回答
ObservableCollection警告
上面提到的(Said Roohullah Allem)
ObservableCollection类的独特之处在于 类支持名为CollectionChanged的事件。
记住这一点……如果你在ObservableCollection中添加了大量的项目,UI也会更新很多次。这可能会阻塞或冻结你的UI。 一种解决方法是创建一个新列表,添加所有的项目,然后将属性设置为新列表。这只会触及UI一次。再次……这是为了添加大量的项目。
无代码解释
对于那些想要答案背后没有任何代码(boom-tish)和一个故事(帮助你记住)的人:
正常收集-没有通知
我偶尔去纽约,我妻子会让我买东西。所以我随身带着购物清单。这个清单上有很多东西,比如:
路易威登手袋(5000美元) 克莱夫·克里斯蒂安的皇家香水(21.5万美元) 古驰太阳镜(2000美元)
哈哈哈,我才不买那种东西呢。所以我把它们划掉,从列表中删除,取而代之的是:
12打Titleist高尔夫球。 12磅重的保龄球。
所以我通常不带东西回家,她从来不会生气,问题是她不知道我从清单上删除了什么,又添加了什么;她没有收到任何通知。
ObservableCollection—在发生更改时通知
现在,每当我从列表中删除一些东西,她就会收到通知。
可观察集合的工作原理与此相同。如果你在其中添加或删除一些东西:有人会收到通知。
他们接到通知后,要么躲起来,要么找掩护!当然,可以通过事件处理程序自定义结果。
很傻的故事,但希望你们现在能记住这个概念。
从Pro c# 5.0和。net 4.5框架
The ObservableCollection<T> class is very useful in that it has the ability to inform external objects when its contents have changed in some way (as you might guess, working with ReadOnlyObservableCollection<T> is very similar, but read-only in nature). In many ways, working with the ObservableCollection<T> is identical to working with List<T>, given that both of these classes implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified. Like any event, CollectionChanged is defined in terms of a delegate, which in this case is NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main() method, which populates an observable collection containing Person objects and wires up the CollectionChanged event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection<Person> people = new ObservableCollection<Person>()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
// Now add a new item.
people.Add(new Person("Fred", "Smith", 32));
// Remove an item.
people.RemoveAt(0);
Console.ReadLine();
}
static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// What was the action that caused the event?
Console.WriteLine("Action for this event: {0}", e.Action);
// They removed something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
Console.WriteLine("Here are the OLD items:");
foreach (Person p in e.OldItems)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine();
}
// They added something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
// Now show the NEW items that were inserted.
Console.WriteLine("Here are the NEW items:");
foreach (Person p in e.NewItems)
{
Console.WriteLine(p.ToString());
}
}
}
}
The incoming NotifyCollectionChangedEventArgs parameter defines two important properties, OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when items are added, removed, relocated, or reset. To discover which of these actions triggered the event, you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be tested against any of the following members of the NotifyCollectionChangedAction enumeration:
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
class FooObservableCollection : ObservableCollection<Foo>
{
protected override void InsertItem(int index, Foo item)
{
base.Add(index, Foo);
if (this.CollectionChanged != null)
this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
}
}
var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;
collection.Add(new Foo());
void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
Foo newItem = e.NewItems.OfType<Foo>().First();
}
ObservableCollection是一个集合,它允许集合外部的代码知道何时发生了对集合的更改(添加、移动、删除)。它在WPF和Silverlight中被大量使用,但它的使用并不局限于这两个领域。代码可以添加事件处理程序,以查看集合何时发生更改,然后通过事件处理程序作出反应,执行一些额外的处理。这可能是更改UI或执行一些其他操作。
下面的代码实际上并没有做任何事情,只是演示了如何在类中附加处理程序,然后使用事件参数以某种方式对更改做出反应。WPF已经内置了许多操作,比如刷新UI,所以在使用observablecollection时可以免费获得这些操作
class Handler
{
private ObservableCollection<string> collection;
public Handler()
{
collection = new ObservableCollection<string>();
collection.CollectionChanged += HandleChange;
}
private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
foreach (var x in e.NewItems)
{
// do something
}
foreach (var y in e.OldItems)
{
//do something
}
if (e.Action == NotifyCollectionChangedAction.Move)
{
//do something
}
}
}
推荐文章
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- AutoMapper:“忽略剩下的?”
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接
- 如何使用。net 4运行时运行PowerShell ?
- 在foreach循环中编辑字典值
- 如何在xml文档中引用泛型类和方法