publicViewModel() { Students = new ObservableCollection<Student>() { new Student(){ Name="Tom",Age=30}, new Student(){ Name="Liza",Age=1}, new Student(){ Name="Tim",Age=30}, }; Students.CollectionChanged += Students_CollectionChanged; }
// 复杂属性 private ObservableCollection<Student> _students = new ObservableCollection<Student>(); public ObservableCollection<Student> Students { get => _students; set { if (_students != value) { _students = value; OnPropertyChanged(nameof(Students)); OnPropertyChanged(nameof(Names)); OnPropertyChanged(nameof(Ages)); } } }
// 派生属性Names,从复杂属性中查询到所有学生的名字,与界面的一个ListBox单向绑定 public List<string> Names=> (from s in Students select s.Name).ToList(); // 派生属性Ages,从复杂属性中查询到所有学生的年龄,与界面的一个ListBox单向绑定 public List<int> Ages=> (from s in Students select s.Age).ToList(); }
publicViewModel() { Students = new ObservableCollection<Student>() { new Student(){ Name="Tom",Age=30}, new Student(){ Name="Liza",Age=1}, new Student(){ Name="Tim",Age=30}, }; Students.CollectionChanged += Students_CollectionChanged; }
// 集合元素变化事件处理器,从复杂属性中查询出数据为派生属性赋值 privatevoidStudents_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Names = new ObservableCollection<string>(from s in Students select s.Name); Ages = new ObservableCollection<int>(from s in Students select s.Age); }
// 复杂属性 private ObservableCollection<Student> _students = new ObservableCollection<Student>(); public ObservableCollection<Student> Students { get => _students; set { if (_students != value) { _students = value; OnPropertyChanged(nameof(Students));
Names = new ObservableCollection<string>(from s in Students select s.Name); Ages = new ObservableCollection<int>(from s in Students select s.Age); } } }
// 派生属性Names,定义成普通属性,与界面的一个ListBox单向绑定 private ObservableCollection<string> _names = new ObservableCollection<string>(); public ObservableCollection<string> Names { get => _names; set { if (_names != value) { _names = value; OnPropertyChanged(nameof(Names)); } } } // 派生属性Ages,定义成普通属性,与界面的一个ListBox单向绑定 private ObservableCollection<int> _ages = new ObservableCollection<int>(); public ObservableCollection<int> Ages { get => _ages; set { if (_ages != value) { _ages = value; OnPropertyChanged(nameof(Ages)); } } } }