我遇到了一個我知道的情況一定很常見的問題,所以我希望解決方案很簡單。我有一個對象,其中包含一個對象列表<>。它還有一些屬性反映了列表<>中的對象的集合數據(實際上是綁定列表<>因此我可以綁定到它)。在我的表單中,我有一個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