在C#中,BindingList<T>
是一个非常重要的集合类,位于 System.ComponentModel
命名空间,主要用于实现数据绑定(Data Binding)场景。
1. 核心作用
BindingList<T>
是 List<T>
的增强版,主要提供以下功能:
自动通知UI更新:当集合内容变化(增删改)时,自动触发事件通知绑定控件(如DataGridView、ListBox等)刷新显示。
支持双向数据绑定:简化UI控件与数据集合的同步,无需手动编写刷新逻辑。
扩展的事件支持:比普通
List<T>
提供更多细粒度的事件(如AddingNew
、ListChanged
)。
2. 关键特性
(1) 自动触发UI更新
BindingList<string> names = new BindingList<string>();
dataGridView1.DataSource = names; // 绑定到DataGridView
names.Add("Alice"); // 添加项时,DataGridView会自动更新显示
names.RemoveAt(0); // 删除项时,UI同步更新
(2) 丰富的事件
事件 | 触发时机 |
---|---|
ListChanged |
列表内容或结构变化时(增删改排序等) |
AddingNew |
添加新项之前 |
AddingNew |
添加新项之前 |
names.ListChanged += (sender, e) =>
{
Console.WriteLine($"列表已更改,类型: {e.ListChangedType}");
};
(3) 支持编辑通知
若 T
实现 INotifyPropertyChanged
,项属性修改时也会通知UI:
public class Person : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set { _name = value; OnPropertyChanged(nameof(Name)); }
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// 使用
BindingList<Person> people = new BindingList<Person>();
dataGridView1.DataSource = people;
people.Add(new Person { Name = "Bob" });
people[0].Name = "Alice"; // 修改属性时,UI自动更新!
3. 典型使用场景
(1) WinForms/WPF数据绑定
// WinForms示例
BindingList<Product> products = new BindingList<Product>();
dataGridView1.DataSource = products;
// WPF示例(需配合ObservableCollection,但BindingList在某些场景仍有用)
listBox.ItemsSource = products;
(2) 实时监控集合变化
var logs = new BindingList<string>();
logs.ListChanged += (s, e) => Console.WriteLine($"日志变更: {logs[e.NewIndex]}");
logs.Add("系统启动"); // 触发事件
4. 注意事项
性能:频繁大规模更新时,考虑使用
ResetItems
通知而非逐项更新。线程安全:需通过
Invoke
在UI线程操作(与所有控件交互一样)。WPF优先用
ObservableCollection<T>
:BindingList
主要面向WinForms设计。