特征
何为可观察的集合?
如果需要集合元素添加和删除的信息,就可以使用ObservableCollection,这个类在WindowsBase程序集定义,这个类是为WPF定义的,如集合发生变化能通知到UI
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace ConsoleApplication34
{
class Program
{
static void Main(string[] args)
{
ObservableCollection<string> obc = new ObservableCollection<string>();
obc.CollectionChanged+=obc_CollectionChanged;
obc.Add("One");
obc.Add("Two");
obc.Insert(1,"Three");
obc.Remove("Three");
}
public static void obc_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Console.WriteLine("action:{0}",e.Action.ToString());
if (e.OldItems!=null)
{
Console.WriteLine("starting index for old item(s):{0}",e.OldStartingIndex);
Console.WriteLine("old item(s):");
foreach (var item in e.OldItems)
{
Console.WriteLine(item);
}
}
if (e.NewItems != null)
{
Console.WriteLine("starting index for new item(s):{0}", e.NewStartingIndex);
Console.WriteLine("new item(s):");
foreach (var item in e.NewItems)
{
Console.WriteLine(item);
}
}
Console.WriteLine();
}
}
}
输出如图:
示例剖析
- 对obc加入CollectionChanged事件obc_CollectionChanged
- 事件属于NotifyCollectionChangedEventHandler的委托类型
- 该委托声明格式为
public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e);
- 根据格式定义方法obc_CollectionChanged
- NotifyCollectionChangedEventArgs 事件参数如图
- 参数e中Action属性是一个枚举类型NotifyCollectionChangedAction
- 查看各个属性的注释得知,OldItems 获取受 Replace、Remove或 Move 操作影响的各项的列表。
- 其它不 一 一列举