我可以为此使用DependencyProperty吗?

本文关键字:DependencyProperty 我可以 | 更新日期: 2023-09-27 17:49:24

我有一个ObservableCollectionStudents。每个学生都有一个年级属性。我想要的AverageGrade属性(所有学生)的工作,而不必按下按钮或创建定时器。我如何在这里使用DependencyProperty这个只读的AverageGrade属性?

<标题> Student.cs h1> <标题> MainWindowViewModel h1> MainWindow.xaml h1> div class="answers">

为什么你想要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));
    }
}

我可以为此使用DependencyProperty吗?

相关文章:
  • 没有找到相关文章