0

我有一个具有以下设置的字典: Dictionary(of String, List(of MyObject)

我已经覆盖了 MyObject.toString 以显示一些不错的东西。

我想创建两个列表框(仅用于显示目的,因此不需要更改字典)。一个包含键,另一个包含所选键的 MyObjects(值)列表。

我尝试了以下方法,但这给了我两次相同的东西:

Dim bs As BindingSource = New BindingSource(dict,Nothing)
    ListBox1.DataSource = bs
    ListBox1.DisplayMember = "Key"
    ListBox2.DataSource = bs
    ListBox2.DisplayMember = "Value"

任何人都知道我该如何解决这个问题?

非常感激。

4

1 回答 1

1

您需要为第一个列表框定义一个事件处理程序(可能是“SelectedIndexChanged”)

例如:

 Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    ListBox2.DataSource = New BindingSource(CType(ListBox1.SelectedItem, KeyValuePair(Of String, myObject())).Value, Nothing)
End Sub

我在测试时将通用列表更改为数组,这是我用来测试的代码:

Dim dict As New Dictionary(Of String, Object())

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    ListBox2.DataSource = New BindingSource(CType(ListBox1.SelectedItem, KeyValuePair(Of String, Object())).Value, Nothing)
End Sub

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    For j As Integer = 1 To 5
        Dim MyList As New List(Of Object)
        For i As Integer = 1 To 5
            MyList.Add(New With {.Index = i, .Pretty = String.Format("Collection {0} DisplayValue {1} ", j, i)})
        Next
        dict.Add(CStr(j), MyList.ToArray)
    Next

    Dim bs As BindingSource = New BindingSource(dict, Nothing)
    ListBox1.DataSource = bs
    ListBox1.DisplayMember = "Key"

End Sub
于 2013-04-19T18:57:44.220 回答