Winforms,数据绑定,列表框和文本框

我的屏幕上有一个ListBox( MyListBox )和一个Textbox( MyTextBox )。

ListBox中填充了List(Of T),它们都是自定义项。

现在我尝试这样做:

ListBox的数据源是List(Of T)。

现在,当项目更改时,我希望文本框更新为ListBox中所选项目的特定属性。

在代码中,这意味着:

 Me.MyListBox.DisplayMember = "SelectionName" Me.MyListBox.ValueMember = "Id" MyTextbox.DataBindings.Add(New Binding("Text", Me._listOfItems, "SelectedItem.Comment", True, DataSourceUpdateMode.OnPropertyChanged)) Me.MyListBox.DataSource = Me._listOfItems 

这不起作用。 但是当我绑定到SelectedValue而不是SelectedItem时,它完美地工作。

_listOfItems声明为:

 Dim _listOfItems As List(Of MyItem) = New List(Of MyItem)() 

MyItem是这样的:

 public class MyItem { public string SelectionName { get; set; } public int Id { get; set; } public string Comment { get; set; } } 

我尝试覆盖MyItemToString() ,以便它可以使用它。 但这也不起作用。

有人想试一试吗?

谢谢!

-Snakiej

我想,最简单的方法之一就是使用BindingSource ,在设计时将它作为ListBox.DataSource属性设置为BindingSource

  1. 在表单上删除BindingSource ;
  2. ListBox.DataSource属性设置为BindingSource ;
  3. 像你实际做的那样设置你的ValueMemberDisplayMember属性;
  4. 使用MyItem.Comment属性为TextBox控件创建DataBinding ,并使用BindingSource作为源代码;
  5. List(Of MyItem)``to your Binding.DataSource`属性;
  6. TextBox应该遵循CurrencyManager.CurrentItem的Comment属性,即当前的ListBox.SelectedItem

实际上,您可能需要实现INotifyPropertyChanged接口以使其正常工作。

但如果这一切都与SelectValue完美配合,为什么不用它呢?