[英]Winforms, databinding, Listbox and textbox
我的屏幕上有一个列表框 ( MyListBox
) 和一个文本框 ( MyTextBox
)。
ListBox 中填充了一个 List(Of T),它们都是自定义项。
现在我尝试这样做:
ListBox 的数据源是 List(Of T)。
现在,当项目更改时,我希望将文本框更新为列表框中所选项目的特定属性。
在代码中,这意味着:
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()
以便它可以使用它。 但这也行不通。
有人愿意试一试吗?
其中一个最简单的方法,我想,会使用BindingSource
,将其设置为ListBox.DataSource
属性为您BindingSource
设计。
BindingSource
;ListBox.DataSource
属性设置为您的BindingSource
;ValueMember
和DisplayMember
属性;TextBox
控件创建DataBinding
,并使用您的BindingSource
作为源,使用您的MyItem.Comment
属性;List(Of MyItem)
分配给您的Binding.DataSource
属性;CurrencyManager.CurrentItem
的 Comment 属性,即当前的ListBox.SelectedItem
。 实际上,您可能需要实现INotifyPropertyChanged
接口才能使其正常工作。
但是,如果这一切都与 SelectValue 完美配合,为什么不直接使用它呢?
下面的代码显示了我是如何做的。 我首先将 ListBox DataSource 设置为具有 BindingList 集合的类。 该类实现 IBindingList。 我有两个要绑定 SelectedItem 的 TextBox。 下面的代码是我的做法:
lbControl.DataSource = SharepointTestBusinessLayer.Control.ListAll();
lbControl.DisplayMember = "ControlName";
lbControl.SelectedIndex = 0;
scTextBoxControlID.DataBindings.Add("Text", this.lbControl.DataSource, "ControlID");
scTextBoxControlName.DataBindings.Add("Text", this.lbControl.DataSource, "ControlName");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.