我有一个 ListBox,它的 DataSource 设置为 BindingList。
BindingList<PairDiff> pairList = new BindingList<PairDiff>();
pairList.RaiseListChangedEvents = true;
listBox1.DataSource = pairList;
BindingList 的类型在其成员之一更新时实现并引发 INotifyPropertyChanged
。
当现有项目中的某些数据发生更改时,ListBox 仍然不会更新它的显示。仅当项目被更改或删除时。
当我调试 listBox.Items 集合时,新数据就在那里。就是不显示!
ListBox中显示的是PairDiffs的ToString
方法。
编辑:
public class PairDiff : INotifyPropertyChanged
{
public Pair pair;
public double diff;
public event PropertyChangedEventHandler PropertyChanged;
public void UpdateDiff(double d) // this is called to update the data in the list
{
diff = d;
PropertyChanged(this, new PropertyChangedEventArgs("diff"));
}
public override string ToString() // this is displayed in the list
{
return pair + " " + diff;
}
}
更新列表框中的数据:
public void UpdateData(Pair pair, double d)
{
var pd = pairList.First((x) => x.pair == pair);
pd.UpdateDiff( d );
}
最佳答案
问题是列表框正在缓存它的值。最简单的解决方案是捕获 ListChanged-Event 并在其中重绘您的列表框:
private void Items_ListChanged(object sender, ListChangedEventArgs e)
{
listbox.Invalidate(); //Force the control to redraw when any elements change
}
我指的是这个article .
关于c# - 列表框未通过数据源更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536907/