我正在尝试从ListBox中获取对象,但是ListBox.Items只返回String,然后我想检查该项目是否被鼠标光标聚焦,我如何做到这一点?
发布于 2021-12-05 20:26:51
克莱门斯帮助我达成了以下解决方案:
解决方案:
项目= CType((mySender.ItemContainerGenerator.ContainerFromIndex(myVar)),ListBoxItem)
mySender是您的ListBox,myVar是您的整数。
发布于 2021-12-05 17:35:34
您有一个处理程序,它迭代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
。第二种方式--不会出现强制转换异常,因为您不是添加String,而是添加ListBoxItem
和.Content
of String
。
显然,您可以声明它为Dim item As String
来使事情正常工作,但是String不具有IsFocused
属性,您可以使用它来显示消息框。
即使您将数组或字符串列表设置为ItemsSource
of您的ListBox
-它也会导致异常。但是数组或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
https://stackoverflow.com/questions/70236475
复制相似问题