ListBox不显示对DataSource的更改

时间:2009-10-22 19:48:51

标签: data-binding listbox c#-2.0

我认为这是一个简单的问题,但我在网上找不到任何信息。我正在使用List将ListBox绑定到BindingSource,如下所示:

List<Customer> customers = MyMethodReturningList();

BindingSource customersBindingSource = new BindingSource();
customersBindingSource.DataSource = customers;

customersListBox.DataSource = customersBindingSource;

现在,当我在customers列表中添加或删除时,我的ListBox会更新(即使不在ResetBindings上使用BindingSource),但如果我更改任何列表中的客户对象,它没有。调用ResetBindings无效。我甚至实现了自己的BindingList,但行为没有改变 Customer类使用属性来访问和修改数据。其ToString()内容显示在列表中。

我在.Net 2.0中使用C#。

有什么想法吗?

由于

5 个答案:

答案 0 :(得分:5)

如果您使用BindingList,则甚至不需要BindingSource

BindingList<Customer> customers = new BindingList<Customer>(MyMethodReturningList());
customersListBox.DataSource = customers;

答案 1 :(得分:4)

好的,这是一个肮脏的修复:我们每次都需要刷新框内容set datasource = null,然后重新绑定它。

它没有更新的原因是因为列表中的对象没有改变,它只检查对象的引用而不是它们的内容。

答案 2 :(得分:2)

列表框中还有一个错误,可能会导致此问题。如果将SelectionMode设置为,则会出现此问题。

作为一种解决方法,我将选择模式设置为One,然后在更新数据源时将其设置为None。

答案 3 :(得分:0)

通过在更新源代码时将数据转换为数组,解决了这个问题。请参阅UpdateData方法。这样您就可以更新组合框而不会丢失ComboBox设置。

class Person {
   public int Id {get; set; }
   public string FirstName{ get; set; }
   public string SurName {get; set; }
}

public Form1()
{
    InitializeComponent();
    comboBox1.DisplayMember = "FirstName";
    comboBox1.ValueMember = "Id";
    comboBox1.DataSource = m_PersonList;
}

public void UpdateData() {
    m_PersonList[0].FirstName = "Firstname1";
    comboBox1.DataSource = m_PersonList.ToArray<Person>();
}

答案 4 :(得分:0)

据我所知,这个问题差不多是在6年前提出来的,但除了解决方法外,我在这里看不到正确的答案。 更改集合中项目的属性时,会为元素(对象)而不是集合引发事件。因此集合看不到更改,也不会刷新绑定控件。所有绑定集合中的元素和大多数通用集合(如List<>)都会收到2个事件,PropertyChangingPropertyChanged。当集合内部元素的属性发生更改时,将触发该事件。您需要做的就是添加一个事件处理程序,该事件处理程序将触发重新绑定或在Collection上引发事件。