Home > Back-end >  How can I get the objects of the ListBox?
How can I get the objects of the ListBox?

Time:12-13

I am trying to fetch the objects from a ListBox, but ListBox.Items only returns Strings, then I want to check if the item is being focused by a mouse cursor, how can I do this?

screenshot 1

screenshot 2

CodePudding user response:

You have a handler, which iterates through ListBox items:

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

You can add items like they are (Strings in example):

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

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

End Sub

or like 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

In first way (when adding strings as they are) - handler will throw exception about fail to cast String to ListBoxItem, because you explicitly declare Dim item As ListBoxItem. In second way - there wouldn't be cast exception, because you add not Strings, but ListBoxItem with .Content of String.

Obviously you can declare it Dim item As String to make things work, but String wouldn't have IsFocused property, which you use to show message box.

Even if you set array or list of strings as ItemsSource of your ListBox - it would cause exception too. But array or list of ListBoxItems, setted as ItemsSource would work in your handler well.

So answer is that mySender.Items isn't collection of ListBoxItems, to which you trying to cast and iterate. You should redefine your ItemsSource to be a collection of ListBoxItems or change type of iterated items from Dim item As ListBoxItem to Dim item As String and lose IsFocused property.

You can also use just SelectedItem without iterating and checking for IsFocused and use safe cast with TryCast and check whether item is ListBoxItem or just use SelectedItem itself and at end call ToString on it:

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

CodePudding user response:

Clemens helped me reach the solution below:

Solution:

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

Where mySender is your ListBox and myVar is your Integer.

  • Related