Winforms、数据绑定、列表框和文本框 [英] Winforms, databinding, Listbox and textbox
问题描述
我的屏幕上有一个列表框 (MyListBox
) 和一个文本框 (MyTextBox
).
I have a ListBox (MyListBox
) on my screen, and a Textbox (MyTextBox
).
ListBox 中填充了一个 List(Of T),都是自定义项.
The ListBox is filled with a List(Of T), which are all custom items.
现在我尝试这样做:
ListBox 的数据源是 List(Of T).
The ListBox' datasource is the List(Of T).
现在,当项目更改时,我希望将文本框更新为列表框中所选项目的特定属性.
Now when an Item changes I want the textbox to be updated to a particular property of the selected item in my 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 时,它可以完美运行.
this does not work. But when I bind to SelectedValue instead of SelectedItem it works perfectly.
_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()
以便它使用它.但这也行不通.
I tried overriding the ToString()
in MyItem
so that it would use that. But that doesn't work either.
有人愿意试一试吗?
推荐答案
我想,最简单的方法之一是使用 BindingSource
,将其设置为 ListBox.DataSource
属性到您的 BindingSource
关于设计.
One of the easiest way, I guess, would be to use a BindingSource
, setting it as the ListBox.DataSource
property to your BindingSource
on design.
- 在表单上放置一个
BindingSource
; - 将您的
ListBox.DataSource
属性设置为您的BindingSource
; - 设置你的
ValueMember
和DisplayMember
属性,就像你实际做的那样; - 为您的
TextBox
控件制作您的DataBinding
,并使用您的BindingSource
作为源,使用您的MyItem.Comment代码>属性;
- 将您的
List(Of MyItem)
分配给您的Binding.DataSource
属性; - 您的 TextBox 应遵循
CurrencyManager.CurrentItem
的 Comment 属性,即当前的ListBox.SelectedItem
.
- Drop a
BindingSource
on your form; - Set your
ListBox.DataSource
property to yourBindingSource
; - Set your
ValueMember
andDisplayMember
properties just like you're actually doing; - Make your
DataBinding
for yourTextBox
control, and use yourBindingSource
as the source, using yourMyItem.Comment
property; - Assign your
List(Of MyItem)
to yourBinding.DataSource
property; - Your TextBox should follow the
CurrencyManager.CurrentItem
's Comment property, that is, the currentlyListBox.SelectedItem
.
实际上,您可能需要实施 INotifyPropertyChanged
接口使其正常工作.
Indeed, you would perhaps need to implement the INotifyPropertyChanged
interface to make it work properly.
但如果这一切都与 SelectValue 完美配合,为什么不直接使用它?
But if this all work perfect with the SelectValue, why don't you just use it?
这篇关于Winforms、数据绑定、列表框和文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!