如何获取 ListBox 的对象?

How can I get the objects of the ListBox?

我想从列表框中获取对象,但 ListBox.Items 只有 returns 字符串,然后我想检查该项目是否被鼠标光标聚焦,我该怎么做这个?

您有一个处理程序,它遍历 ListBox 个项目:

Private Sub ListBox_PreviewMouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs) Handles listBox.PreviewMouseLeftButtonDown

    Dim mySender As ListBox = sender
    Dim item As ListBoxItem

    For Each item In mySender.Items

        If item.IsFocused Then
            MsgBox(item.ToString)
        End If

    Next

End Sub

您可以按原样添加项目(例如 Strings):

Private Sub OnWindowLoad(sender As Object, e As RoutedEventArgs)

    listBox.Items.Add("Item1")
    listBox.Items.Add("Item2")
    listBox.Items.Add("Item3")

End Sub

或喜欢ListBoxItems:

Private Sub OnWindowLoad(sender As Object, e As RoutedEventArgs)

    listBox.Items.Add(New ListBoxItem With { .Content = "Item1" })
    listBox.Items.Add(New ListBoxItem With { .Content = "Item2" })
    listBox.Items.Add(New ListBoxItem With { .Content = "Item3" })

End Sub

第一种方式(按原样添加字符串时)- 处理程序将抛出有关无法将 String 转换为 ListBoxItem 的异常,因为您明确声明了 Dim item As ListBoxItem。第二种方式 - 不会有转换异常,因为你添加的不是字符串,而是 ListBoxItemString.Content

显然,您可以声明它 Dim item As String 以使其正常工作,但字符串不会有 IsFocused 属性,您可以使用它来显示消息框。

即使您将数组或字符串列表设置为 ListBoxItemsSource - 它也会导致异常。但是 ListBoxItems 的数组或列表设置为 ItemsSource 将在您的处理程序中运行良好。

所以答案是 mySender.Items 不是 ListBoxItem 的集合,您试图对其进行转换和迭代。您应该将 ItemsSource 重新定义为 ListBoxItems 的集合,或者将迭代项的类型从 Dim item As ListBoxItem 更改为 Dim item As String 并丢失 IsFocused 属性.

您也可以只使用 SelectedItem 而无需迭代和检查 IsFocused 并使用带有 TryCast 的安全转换并检查项目是否为 ListBoxItem 或仅使用 SelectedItem 本身最后在其上调用 ToString:

Dim mySender As ListBox = sender
Dim item

If mySender.SelectedItem IsNot Nothing Then
    item = TryCast(mySender.SelectedItem, ListBoxItem)

    If item Is Nothing Then
        item = mySender.SelectedItem
    End If

    MsgBox(item.ToString)

End If

Clemens 帮助我找到了以下解决方案:

解法:

item = CType((mySender.ItemContainerGenerator.ContainerFromIndex(myVar)), ListBoxItem)

其中 mySender 是您的列表框,myVar 是您的整数。