我試圖從 ListBox 中獲取物件,但 ListBox.Items 只回傳字串,然后我想檢查該專案是否被滑鼠游標聚焦,我該怎么做?


uj5u.com熱心網友回復:
你有一個處理程式,它遍歷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 ListBoxItemtoDim item As String和 lossIsFocused屬性更改。
您還可以使用 justSelectedItem而無需迭代和檢查IsFocused并使用安全轉換TryCast并檢查 item 是否為 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
uj5u.com熱心網友回復:
克萊門斯幫我找到了以下解決方案:
解決方案:
item = CType((mySender.ItemContainerGenerator.ContainerFromIndex(myVar)), ListBoxItem)
其中mySender是您的 ListBox,而myVar是您的整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/375357.html
