我正在尝试从ListBox中获取对象,但是ListBox.Items只返回String,然后我想检查该项目是否被鼠标光标聚焦,我如何做到这一点?
您有一个处理程序,它迭代
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
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