网站开发需要哪些流程,石家庄网络公司有哪些,建设企业网站的目的,孝昌网站建设ObservableCollection 类提供了一种实时监测集合变化的机制#xff0c;可以通过订阅 CollectionChanged 事件来响应集合的添加、移除和重置等变化。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;class Program
{static void …ObservableCollection 类提供了一种实时监测集合变化的机制可以通过订阅 CollectionChanged 事件来响应集合的添加、移除和重置等变化。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;class Program
{static void Main(){ObservableCollectionstring collection new ObservableCollectionstring();// 订阅 CollectionChanged 事件collection.CollectionChanged Collection_CollectionChanged;// 向集合中添加元素collection.Add(item 1);collection.Add(item 2);collection.Add(item 3);// 从集合中移除元素collection.Remove(item 2);// 清空集合collection.Clear();}static void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){if (e.Action NotifyCollectionChangedAction.Add){Console.WriteLine(元素已添加);foreach (string item in e.NewItems){Console.WriteLine(item);}}else if (e.Action NotifyCollectionChangedAction.Remove){Console.WriteLine(元素已移除);foreach (string item in e.OldItems){Console.WriteLine(item);}}else if (e.Action NotifyCollectionChangedAction.Reset){Console.WriteLine(集合已重置);}}
}Tips 在 ObservableCollection 中如果你更改了集合中的元素例如修改了元素的属性这将会触发 CollectionChanged 事件。
但是如果你只是替换了集合中的元素即通过索引直接赋值这将不会触发 CollectionChanged 事件