
AI
使用WPF ObservableCollection
csharp// 定义一个Person类public class Person{ public string Name { get; set; } public int Age { get; set; }}// 在ViewModel中声明一个ObservableCollection<Person>类型的属性public class MAInViewModel : INotifyPropertyChanged{ private ObservableCollection<Person> _personList; public ObservableCollection<Person> PersonList { get { return _personList; } set { _personList = value; OnPropertyChanged(); } } public MAInViewModel() { // 初始化PersonList集合 PersonList = new ObservableCollection<Person>(); // 添加几个Person对象 PersonList.Add(new Person { Name = "张三", Age = 20 }); PersonList.Add(new Person { Name = "李四", Age = 25 }); PersonList.Add(new Person { Name = "王五", Age = 30 }); } // INotifyPropertyChanged接口的实现代码省略}在上述代码中,我们定义了一个Person类,包含了Name和Age两个属性。然后在MAInViewModel中声明了一个ObservableCollectionxaml<ListBox ItemsSource="{Binding PersonList}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>BindingListcsharp// 在ViewModel中声明一个BindingList<Person>类型的属性public class MAInViewModel : INotifyPropertyChanged{ private BindingList<Person> _personList; public BindingList<Person> PersonList { get { return _personList; } set { _personList = value; OnPropertyChanged(); } } public MAInViewModel() { // 初始化PersonList集合 PersonList = new BindingList<Person>(); // 添加几个Person对象 PersonList.Add(new Person { Name = "张三", Age = 20 }); PersonList.Add(new Person { Name = "李四", Age = 25 }); PersonList.Add(new Person { Name = "王五", Age = 30 }); } // INotifyPropertyChanged接口的实现代码省略}在上述代码中,我们同样定义了一个Person类,并在MAInViewModel中声明了一个BindingListxaml<ListBox ItemsSource="{Binding PersonList}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>在本文中,我们分别介绍了WPF中的ObservableCollectionCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号