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

Sna*_*ake 6 c# vb.net data-binding winforms

MyListBox我的屏幕上有一个ListBox()和一个Textbox(MyTextBox).

ListBox中填充了List(Of T),它们都是自定义项.

现在我尝试这样做:

ListBox的数据源是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
Run Code Online (Sandbox Code Playgroud)

这不起作用.但是当我绑定到SelectedValue而不是SelectedItem时,它完美地工作.

_listOfItems声明为这样的:

Dim _listOfItems As List(Of MyItem) = New List(Of MyItem)()
Run Code Online (Sandbox Code Playgroud)

MyItem这是哪个:

public class MyItem
{
    public string SelectionName { get; set; }
    public int Id { get; set; }
    public string Comment { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我尝试重写ToString()in MyItem以便它会使用它.但这也不起作用.

有人想试一试吗?

谢谢!

-Snakiej

Wil*_*ler 10

我想,最简单的方法之一就是使用a BindingSource,将其设置为ListBox.DataSourceBindingSource设计的属性.

  1. 放下BindingSource你的表格;
  2. 将您的ListBox.DataSource财产设置为您的BindingSource;
  3. 设置你的ValueMemberDisplayMember属性就像你实际做的那样;
  4. 让您DataBindingTextBox控制权,并使用您BindingSourceMyItem.Comment财产作为来源;
  5. 分配你的List(Of MyItem)``to yourBinding.DataSource`属性;
  6. 你的TextBox应该遵循CurrencyManager.CurrentItem'Comment属性,即当前的属性ListBox.SelectedItem.

实际上,您可能需要实现INotifyPropertyChanged接口以使其正常工作.

但如果这一切都与SelectValue完美配合,为什么不用它呢?