.net中ObservableCollection有什么用?
当前回答
ObservableCollection本质上与常规集合类似,只是它实现了 的接口:
INotifyCollectionChanged, INotifyPropertyChanged
因此,当您想知道集合何时发生更改时,它非常有用。触发一个事件,告诉用户添加/删除或移动了哪些条目。
更重要的是,当在表单上使用数据绑定时,它们非常有用。
其他回答
最大的用途之一是可以将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);
}
从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,
}
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();
}
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
}
}
}
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 如何在。net中创建和使用资源
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务