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。每当分数在列中发生变化时,我希望“总计”列自动计算总计并显示。
答案 0 :(得分:1)
注1
简而言之 - 您应该订阅所有“分数”的INotifyPropertyChanged.PropertyChanged事件,并且在事件处理程序中您应该重新计算您的总分数。但问题是你还应该监控你的Scores集合中的变化(当然,如果你需要的话)。
作为一个非常有用的助手,您可以尝试使用我的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
另见this article。它将教会如何避免通知中的“魔术字符串”(如RaisePropertyChanged("Scores")
和e.PropertyName == "Score"
)。
注3
而不是
StudentAverage = (from score in Scores select score.Score).Sum();
最好使用
StudentAverage = Scores.Sum(score => score.Score);
但这不一定,这只是我的编码风格:)
顺便说一句,为什么它是混合的 - “平均”和“总和”?这是错误吗?