observablecollection - Observable collection Raise property changed -
private observablecollection<scores> _scores; public observablecollection<scores> scores { { 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 { { return _studentaverage; } set { _studentaverage = value; raisepropertychanged("studentaverage"); } } private string _gradeyear; public string gradeyear { { return _gradeyear; } set { _gradeyear = value; raisepropertychanged("studentgrade"); } } private void recalculate() { studentaverage = (from score in scores select score.score).sum(); } hi, how can notification when score changes inside observablecollection can recalculate.
actually binding whole entity gridview. whenever score changes in column want total column automatically calculate total , display.
note 1
in nutshell - should subscribe inotifypropertychanged.propertychanged event of "scores", , in event handler should recalc totalscore. problem should monitor changes in scores collection (if need it, of course).
as useful helper can try use extended observablecollection. class contains itempropertychangedevent, should write like:
private observablecollectionex<scores> _scores; public observablecollectionex<scores> scores { { 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(); } note 2
take @ this article. teach how avoid "magic strings" in notifications (like raisepropertychanged("scores") , e.propertyname == "score").
note 3
instead of
studentaverage = (from score in scores select score.score).sum(); it's better use
studentaverage = scores.sum(score => score.score); but not necessarily, style of coding :)
btw, why it's mixed - "average" , "sum"? mistake?
Comments
Post a Comment