我遇到了一个我知道的情况一定很常见的问题,所以我希望解决方案很简单。我有一个对象,其中包含一个对象列表<>。它还有一些属性反映了列表<>中的对象的集合数据(实际上是绑定列表<>因此我可以绑定到它)。在我的表单中,我有一个DataGridView用于List,还有一些其他字段用于聚合数据。我无法弄清楚如何在DataGridView中的值发生更改时触发刷新聚合数据。Winforms包含列表的数据绑定对象<T>
我试着在列表中的对象的属性发生更改时引发PropertyChanged事件,但似乎没有刷新聚合数据的显示。如果我访问一个聚合属性(例如,将其显示在消息框中),则会刷新主窗体上的文本框。
下面是一些简单的代码来说明我想要做的事:
namespace WindowsFormsApplication1 {
public class Person {
public int Age {
get;
set;
}
public String Name {
get;
set;
}
}
public class Roster : INotifyPropertyChanged {
public BindingList<Person> People {
get;
set;
}
public Roster() {
People = new BindingList<Person>();
}
private int totalage;
public int TotalAge {
get {
calcAges();
return totalage;
}
set {
totalage = value;
NotifyPropertyChanged("TotalAge");
}
}
private void calcAges() {
int total = 0;
foreach (Person p in People) {
total += p.Age;
}
TotalAge = total;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged (String info) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
}
这看起来与http://stackoverflow.com/questions/601320/winforms-data-binding-bind-to-objects-in-a-list非常相似,可能是它的重复。 – 2009-07-13 15:09:42