Winforms、数据绑定、Listbox和Textbox

7

我在屏幕上有一个列表框(MyListBox)和一个文本框(MyTextBox)。

列表框填充了一个自定义项的泛型列表(List(Of T))。

现在我尝试做到这一点:

列表框的数据源是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()方法,以便它可以使用该方法。但这也不起作用。

有人愿意试试吗?

2个回答

12
我猜最简单的方法是使用BindingSource,将其设置为设计中您的BindingSourceListBox.DataSource属性。
  1. 在窗体上放置BindingSource
  2. ListBox.DataSource属性设置为BindingSource
  3. 像您实际进行的操作一样设置ValueMemberDisplayMember属性;
  4. 对您的TextBox控件进行DataBinding,并使用您的BindingSource作为源,使用您的MyItem.Comment属性;
  5. List(Of MyItem)分配给您的Binding.DataSource属性;
  6. 您的TextBox应该遵循当前被选中的ListBox.SelectedItem的Comment属性,即CurrencyManager.CurrentItem
事实上,您可能需要实现INotifyPropertyChanged接口才能使其正常工作。
但是,如果这与SelectValue完美配合,为什么不直接使用呢?

选定的值是Id,我需要评论。而且我不能用它来调用数据库 :) 我会尝试你的解决方案! - Snake
我明白了!你说得对,如果你想要向用户提供选择选项,我们不应该使用Id。= P - Will Marcouiller
不需要选项5 :) 对于选项4:我使用以下绑定:new Binding("Text", bindingSource1, "Comment", ...),因为它已经使用了bindingSource的.Current属性! 谢谢! - Snake

0
以下代码展示了我的做法。首先,我将我的ListBox数据源设置为一个带有BindingList集合的类。该类实现了IBindingList接口。我想要将SelectedItem绑定到两个文本框中。下面的代码是我如何做到的:
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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接