的WinForms,数据绑定,列表框和文本框 [英] Winforms, databinding, Listbox and textbox
问题描述
我有一个列表框( MyListBox
)我的屏幕上,和一个文本框( MyTextBox
)。
I have a ListBox (MyListBox
) on my screen, and a Textbox (MyTextBox
).
列表框填充一个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; }
}
我试图重写的ToString()
在 MyItem
,这样它会利用这一点。但是,这也不行。
I tried overriding the ToString()
in MyItem
so that it would use that. But that doesn't work either.
有人关心给它一个尝试一下呢?
Anybody care to give it a try?
谢谢!
-Snakiej
推荐答案
最简单的一种方式,我猜,会是使用 的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
属性,就像你实际做; - 请您
数据绑定
为你的文本框
控制,并使用你的的BindingSource
为源,使用MyItem.Comment
财产; - 分配你的
列表(中MyItem)``你
Binding.DataSource`财产; - 您的文本框应该遵循
CurrencyManager.CurrentItem
的Comment属性,也就是当前列表框。的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 your
Binding.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屋!