您有一个处理程序,它遍历 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。第二种方式 - 不会出现强制转换异常,因为您添加的不是字符串,而是 ListBoxItem 和 .Content 的 String。
显然,您可以声明它Dim item As String 以使事情正常进行,但 String 不会有 IsFocused 属性,您可以使用它来显示消息框。
即使您将数组或字符串列表设置为ItemsSource 的ListBox - 它也会导致异常。但是ListBoxItems 的数组或列表设置为ItemsSource 可以在您的处理程序中正常工作。
所以答案是 mySender.Items 不是 ListBoxItems 的集合,您尝试对其进行投射和迭代。您应该将您的 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