3
private ObservableCollection<Scores> _scores; 
    public ObservableCollection<Scores> Scores
    {
        get
        {
            return _scores;
        }
        set
        {
            _scores = value;
            RaisePropertyChanged("Scores");
            Recalculate();
        } 
    }

    public int RowNumber { get; set; }
    public string StudentId { get; set; }
    public string StudentName { get; set; }

    private double _studentAverage;
    public double StudentAverage
    {
        get
        {
            return _studentAverage;
        }
        set
        {
            _studentAverage = value;
            RaisePropertyChanged("StudentAverage");
        }
    }

    private string _gradeYear;
    public string GradeYear
    {
        get
        {
            return _gradeYear;
        }
        set
        {
            _gradeYear = value;
            RaisePropertyChanged("StudentGrade");
        }
    }


    private void Recalculate()
    {
        StudentAverage = (from score in Scores select score.Score).Sum();
    }

嗨,当 ObservableCollection 中的分数发生变化时,我怎样才能得到通知,以便我可以重新计算。

实际上,我将整个实体绑定到 Gridview。每当列中的分数发生变化时,我希望我的总计列自动计算总计并显示。

4

1 回答 1

2

注1

简而言之-您应该订阅所有“分数”的 INotifyPropertyChanged.PropertyChanged 事件,并且在事件处理程序中您应该重新计算您的 TotalScore。但问题是您还应该监控您的分数集合中的变化(当然,如果您需要它)。

作为一个非常有用的助手,您可以尝试使用我的Extended ObservableCollection。这个类已经包含 ItemPropertyChangedEvent,所以你应该只写如下内容:

private ObservableCollectionEx<Scores> _scores; 

public ObservableCollectionEx<Scores> Scores
{
    get
    {
        return _scores;
    }
    set
    {
        if (_scores == value) return;
        if (_scores != null)
            _scores.ItemPropertyChanged -= OnItemPropertyChanged;
        _scores = value;
        if (_scores != null)
            _scores.ItemPropertyChanged += OnItemPropertyChanged;
        RaisePropertyChanged("Scores");
        Recalculate();
    } 
}

void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "Score")
        Recalculate();
}

笔记2

看看这篇文章。它将教如何避免通知中的“魔术字符串”(如RaisePropertyChanged("Scores")e.PropertyName == "Score")。

注3

代替

StudentAverage = (from score in Scores select score.Score).Sum();

最好使用

StudentAverage = Scores.Sum(score => score.Score);

但这不一定,这只是我的编码风格:)

顺便说一句,为什么它是混合的 - “平均”和“总和”?这是错误吗?

于 2012-06-06T12:26:05.050 回答