更改BindingList的默认行为

时间:2014-09-10 21:18:53

标签: c# bindinglist

我正在研究BindingList,我想改变它的默认行为,以便在我手动引发事件时刷新它所包含的DataGridView。在我的情况下,我每隔1秒用foreach循环中的数据更新BindingList,并且在所有内容都是最新的之后我想刷新DataGridView。我该怎么办?

2 个答案:

答案 0 :(得分:2)

查看MSDN文档,看起来您可以从BindingList<T>派生并覆盖BindingList<T>.SupportsChangeNotificationCore以关闭列表更改通知:

public class MyBindingList<T> : BindingList<T>
{
    protected override bool SupportsChangeNotificationCore 
    { 
        get { return false; } 
    }
}

然后,当您需要更新DataGridView时,您应该可以调用ResetBindings()

但是,如果通过&#34;更新BindingList&#34;,您只是意味着添加/删除项目,那么您可以将BindingList<T>.RaiseListChangedEvents设置为false以关闭列表更改的通知:

var bindingList = new BindingList<string>();
bindingList.RaiseListChangedEvents = false; // turn off notifications
bindingList.Add("foo"); // no notifications raised
...
bindingList.RaiseListChangedEvents = true; // turn on notifications
bindingList.ResetBindings(); // raise notifications

答案 1 :(得分:0)

你可以:

  1. 使用BindingSource来包装bindinglist
  2. datagridView绑定到bindingSource
  3. 设置BindingSource.RaiseListChangedEvents = false,因此不会引发ListChanged事件(datagrid不听取更改)
  4. 更新列表
  5. 重置RaiseListChangedEvents并调用BindingSource.ResetBindings(false)向所有绑定组件发出信号以刷新数据
  6. 通常你也可以使用BindingSource.SuspendBinding来阻止更改,并且ResumeBinding可以恢复,但这对DataGridView不起作用,只有像TextBox这样的简单控件(参见remarks on msdn