publicclassPerson { publicstring? Name { get; set; } publicstring? Home { get; set; } }
創建Person對象列表:
// 創建一個Person對象的列表 List<Person> people = new List<Person>() { new Person {Name = "張三",Home = "武漢" }, new Person {Name = "李四",Home = "南昌" }, new Person {Name = "王五",Home = "福州" }, };
publicstring Name { get { return _name; } set { _name = value; // Call OnPropertyChanged whenever the property is updated OnPropertyChanged("Name"); } } privatestring? _home;
publicstring Home { get { return _home; } set { _home = value; // Call OnPropertyChanged whenever the property is updated OnPropertyChanged("Home"); } }
// Declare the event publicevent PropertyChangedEventHandler? PropertyChanged; // Create the OnPropertyChanged method to raise the event protectedvoidOnPropertyChanged(string name) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(name)); } }
實現了INotifyPropertyChanged接口。
創建數據源:
// 創建一個Student對象的列表 BindingList<Student> students = new BindingList<Student>() { new Student { Name = "張三", Home = "武漢" }, new Student { Name = "李四", Home = "南昌" }, new Student { Name = "王五", Home = "福州" }, };
注意這里使用的是BindingList<T>而不是List<T>。
BindingList<T>與List<T>的區別
BindingList和 List都是用于存儲對象的集合,但它們之間有一些關鍵的區別。
數據綁定支持:BindingList是為數據綁定設計的,它實現了 IBindingList 接口。這意味著當 BindingList中的數據發生更改時(例如,添加、刪除或修改項),它會自動通知綁定到它的任何 UI 控件。這對于 Windows Forms 或 WPF 這樣的 UI 框架非常有用,因為它們可以自動更新以反映數據的更改。相比之下,List不支持數據綁定。