使用WPF ObservableCollection
csharp// 定义一个Person类public class Person{ public string Name { get; set; } public int Age { get; set; }}// 在ViewModel中声明一个ObservableCollection在上述代码中,我们定义了一个Person类,包含了Name和Age两个属性。然后在MainViewModel中声明了一个ObservableCollection类型的属性public class MainViewModel : INotifyPropertyChanged{ private ObservableCollection _personList; public ObservableCollection PersonList { get { return _personList; } set { _personList = value; OnPropertyChanged(); } } public MainViewModel() { // 初始化PersonList集合 PersonList = new ObservableCollection (); // 添加几个Person对象 PersonList.Add(new Person { Name = "张三", Age = 20 }); PersonList.Add(new Person { Name = "李四", Age = 25 }); PersonList.Add(new Person { Name = "王五", Age = 30 }); } // INotifyPropertyChanged接口的实现代码省略}
xamlBindingList
csharp// 在ViewModel中声明一个BindingList在上述代码中,我们同样定义了一个Person类,并在MainViewModel中声明了一个BindingList类型的属性public class MainViewModel : INotifyPropertyChanged{ private BindingList _personList; public BindingList PersonList { get { return _personList; } set { _personList = value; OnPropertyChanged(); } } public MainViewModel() { // 初始化PersonList集合 PersonList = new BindingList (); // 添加几个Person对象 PersonList.Add(new Person { Name = "张三", Age = 20 }); PersonList.Add(new Person { Name = "李四", Age = 25 }); PersonList.Add(new Person { Name = "王五", Age = 30 }); } // INotifyPropertyChanged接口的实现代码省略}
xaml在本文中,我们分别介绍了WPF中的ObservableCollection