WPF VB.net ListBox how to get selected item index or a sorted & grouped list relative to item source

listboxvb.netwpf

Good evening all,

Firstly thank you for the time taken to read this.
I'm having some difficulty with a sorted & grouped listbox in WPF vb.net 3.5 that has an items source bound to an ObservableCollection.

What I want to be able to do is to retrieve a piece of data from the ObservableCollection items source depending on what item in the listbox the user has selected.

I've almost got it working but because the listbox is sorted it does not match the index of the items source.

Here is the code that I have so far:

Dim i As Integer = lstBox1.Items.IndexOf(lstBox1.SelectedItem)
MessageBox.Show(myListSource.Item(i).Description.ToString, "Source Description")

As I previously mentioned, because the lstBox is sorted and also grouped the index's don't match up.

Does anyone know how I can get the correct information I want from the List Source depending on the selected item in the list box?

Again, thank you very much for your time,

Rob

Best Answer

You can bind the ItemsSource to the ObservableCollection<Foo> and bind the SelectedItem to an instance of Foo.

That way, you have removed the dependency on the index of the list - you can group and sort as you wish - by selecting an item in the list, the current instance in you backing class (probably a ViewModel) will update through the Binding.

It should look something like this

<ListBox
    ItemsSource="{Binding MyCollection}"
    SelectedItem="{Binding CurrentSelection}" />

and in the code (ViewModel) acting as the DataContext for the view...

Private _myCollection As ObservableCollection(Of Foo)
Public Property MyCollection As ObservableCollection(Of Foo)
Get
    Return _myCollection
End Get

Private _currentItem As Foo
Public Property CurrentItem As Foo
Get
    Return _currentItem
End Get
Set(ByVal value As Foo)
    Me._currentItem = value
End Set

(with apologies if I have the vb syntax wrong)

So if you need to access the ListBox's SelectedItem in your ViewModel, you can just use the CurrentItem property...

MessageBox.Show(CurrentItem.Description.ToString, "Source Description")
Related Topic