繁体   English   中英

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

[英]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; }
}

我尝试覆盖MyItemToString()以便它可以使用它。 但这也行不通。

有人愿意试一试吗?

其中一个最简单的方法,我想,会使用BindingSource ,将其设置为ListBox.DataSource属性为您BindingSource设计。

  1. 在您的表单上放置一个BindingSource
  2. 将您的ListBox.DataSource属性设置为您的BindingSource
  3. 像实际操作一样设置ValueMemberDisplayMember属性;
  4. 为您的TextBox控件创建DataBinding ,并使用您的BindingSource作为源,使用您的MyItem.Comment属性;
  5. 将您的List(Of MyItem)分配给您的Binding.DataSource属性;
  6. 您的 TextBox 应遵循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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM