.net中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,
}
其他回答
无代码解释
对于那些想要答案背后没有任何代码(boom-tish)和一个故事(帮助你记住)的人:
正常收集-没有通知
我偶尔去纽约,我妻子会让我买东西。所以我随身带着购物清单。这个清单上有很多东西,比如:
路易威登手袋(5000美元) 克莱夫·克里斯蒂安的皇家香水(21.5万美元) 古驰太阳镜(2000美元)
哈哈哈,我才不买那种东西呢。所以我把它们划掉,从列表中删除,取而代之的是:
12打Titleist高尔夫球。 12磅重的保龄球。
所以我通常不带东西回家,她从来不会生气,问题是她不知道我从清单上删除了什么,又添加了什么;她没有收到任何通知。
ObservableCollection—在发生更改时通知
现在,每当我从列表中删除一些东西,她就会收到通知。
可观察集合的工作原理与此相同。如果你在其中添加或删除一些东西:有人会收到通知。
他们接到通知后,要么躲起来,要么找掩护!当然,可以通过事件处理程序自定义结果。
很傻的故事,但希望你们现在能记住这个概念。
最大的用途之一是可以将UI组件绑定到一个组件上,如果集合的内容发生变化,它们将适当地响应。例如,如果你将一个ListView的ItemsSource绑定到一个,如果你修改了集合,ListView的内容将自动更新。
编辑: 下面是一些来自MSDN的示例代码: http://msdn.microsoft.com/en-us/library/ms748365.aspx
在c#中,将ListBox连接到集合非常简单
listBox.ItemsSource = NameListData;
但是如果你还没有将列表作为静态资源连接起来并定义NameItemTemplate,你可能想要重写PersonName的ToString()。例如:
public override ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
ObservableCollection本质上与常规集合类似,只是它实现了 的接口:
INotifyCollectionChanged, INotifyPropertyChanged
因此,当您想知道集合何时发生更改时,它非常有用。触发一个事件,告诉用户添加/删除或移动了哪些条目。
更重要的是,当在表单上使用数据绑定时,它们非常有用。
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();
}
它是一个集合,用于通知大多数UI在集合中发生变化,它支持自动通知。
主要用于WPF,
假设你有一个带有列表框和add按钮的UI,当你点击按钮时,一个类型为suppose person的对象会被添加到observable集合中,你将这个集合绑定到Listbox的ItemSource,所以只要你在集合中添加了一个新项目,Listbox就会更新自己并在其中添加一个项目。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本