本文主要是介绍C# 关于当ObservableCollection增删查改元素时,触发事件用例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ObservableCollection 类提供了一种实时监测集合变化的机制,可以通过订阅 CollectionChanged 事件来响应集合的添加、移除和重置等变化。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;class Program
{static void Main(){ObservableCollection<string> collection = new ObservableCollection<string>();// 订阅 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 事件
这篇关于C# 关于当ObservableCollection增删查改元素时,触发事件用例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!