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; } }
我尝试覆盖MyItem
的ToString()
,以便它可以使用它。 但这也不起作用。
有人想试一试吗?
谢谢!
-Snakiej
我想,最简单的方法之一就是使用BindingSource
,在设计时将它作为ListBox.DataSource
属性设置为BindingSource
。
- 在表单上删除
BindingSource
; - 将
ListBox.DataSource
属性设置为BindingSource
; - 像你实际做的那样设置你的
ValueMember
和DisplayMember
属性; - 使用
MyItem.Comment
属性为TextBox
控件创建DataBinding
,并使用BindingSource
作为源代码; - 将
List(Of MyItem)``to your
Binding.DataSource`属性; - TextBox应该遵循
CurrencyManager.CurrentItem
的Comment属性,即当前的ListBox.SelectedItem
。
实际上,您可能需要实现INotifyPropertyChanged
接口以使其正常工作。
但如果这一切都与SelectValue完美配合,为什么不用它呢?