我可以为此使用DependencyProperty吗?
本文关键字:DependencyProperty 我可以 | 更新日期: 2023-09-27 17:49:24
我有一个ObservableCollection
与Students
。每个学生都有一个年级属性。我想要的AverageGrade
属性(所有学生)的工作,而不必按下按钮或创建定时器。我如何在这里使用DependencyProperty
这个只读的AverageGrade
属性?
为什么你想要DP,它看起来像正常的VM属性,照顾这个。您需要的是每当添加新学生或更改现有学生的成绩时,必须更新AverageGrade。
可以试试这个方法:
class MainWindowViewModel
{
#region Constructors
public MainWindowViewModel()
{
Students = new ObservableCollection<Student>();
Students.Add(new Student("Frank", "Sinatra", 7));
Students.Add(new Student("Bart", "Simpson", 6));
Students.CollectionChanged += (s, e) => AverageGrade = this.GetAverageGrade();
foreach (var student in Students)
{
student.PropertyChanged += OnStudentPropertyChanged;
}
AverageGrade = this.GetAverageGrade();
}
private void OnStudentPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Grade")
{
AverageGrade = this.GetAverageGrade();
}
}
#endregion
#region Properties
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get { return _students; }
set
{
_students = value;
OnPropertyChanged("Students");
}
}
private double average;
public double AverageGrade
{
get
{
return this.average;
}
set
{
this.average = value;
OnPropertyChanged("AverageGrade");
}
}
public double GetAverageGrade()
{
return this.Students.Sum(s => s.Grade) / Students.Count;
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
标题>标题>