2010-05-25 104 views
5

我在我的屏幕上有一个列表框(MyListBox)和一个文本框(MyTextBox)。Winforms,数据绑定,列表框和文本框

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; } 
} 

我试图重写ToString()MyItem,这样它会利用这一点。但那也行不通。

有人在乎试试看吗?

谢谢!

-Snakiej

回答

9

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

  1. 在表单上放一个BindingSource;
  2. 将您的ListBox.DataSource属性设置为您的BindingSource;
  3. 设置您的ValueMemberDisplayMember属性,就像您实际在做的一样;
  4. 使您的DataBinding为您的TextBox控制,并使用您的BindingSource作为来源,使用您的MyItem.Comment属性;
  5. 指定您的List(Of MyItem)``to your Binding.DataSource`属性;
  6. 您的文本框应该遵循CurrencyManager.CurrentItem的Comment属性,即当前的ListBox.SelectedItem

的确,您可能需要实施INotifyPropertyChanged接口才能使其正常工作。

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

+0

SelectedValue是Id,我需要评论。我不能用它来调用数据库:)我会尝试你的解决方案! – Snake 2010-05-25 13:05:13

+0

我懂了!你是对的,如果你想要给用户提供一个选择选择,我们不要用Id来做。= P – 2010-05-25 13:06:44

+0

选项5不需要:)和选项4:我使用此绑定: 新的绑定(“Text”,bindingSource1,“Comment”,...),因为它已经使用bindingSource的.Current属性! 谢谢! – Snake 2010-05-25 13:13:07