c# - 列表框未通过数据源更新

标签 c# .net winforms listbox datasource

我有一个 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/

相关文章:

c# - 将字节数组转换为字符串并打印到控制台

c# - 将 System.Diagnostics.ProcessStartInfo StandardOutput 读取为字节而不是字符

.net - 实际显示时,我的控件大小怎么会是 NaN?

c# - 为什么我会看到使用 native 代码的速度提高了约 20%?

c# - 为什么 ControlCollection 不抛出 InvalidOperationException?

c# - params 关键字可以通过 WSDL 定义来表达吗

c# - 将新元组转换为旧元组会产生编译错误

C# 从视频文件的一部分中提取帧

.net - Matlab 无法加载 .NET 程序集

.net - Split Container SplitterDistance 无需用户干预即可更改