My WPF application has a ListBox in it. The ListBox's ItemsSource property is set to a collection of objects I have defined. These all descend from UserControl.
I need to loop over the items in the ListBox in the order that they appear on screen. I believe I can do this by looping over the ListBox's Items collection.
I believe that the objects inthis collection are of type ListBoxItem. How do I get at the objects of my type from the ListBoxItem? In other words, how do I get at the instance of my class descended from UserControl from the ListBoxItem?
EDIT:
Additional information I should have included in the first place:
I need to loop over the Items in the order that they appear in the ListBox so I can select the one closest to the top that matches a particular condition. After I find the one I’m interested in, I need to select it. It’s a single select ListBox, so only one item at a time will be selected.
So, my question really is: How do I select the Item?
Not that it matters, but the reason my type descends from UserControl is because it contains a number of controls that need to be diplayed in the ListBox for each item.
I found that I needed to loop over the items in the
Itemscollection in reverse order. I’m not sure why this is, I thought that theItemscollection held everything in the order they appear on screen. Perhaps it’s because the ListBox is sorted in descending order on aDateTimeproperty of the underlying data?In any case, since I had to loop backwards, I ended up having to write a
forloop that started at the end of the collection and worked its way forwards. Since I now had the index of the item I wanted to select, it was easy to just setListBox.SelectedIndexto that index.