RobHurd
RobHurd

Reputation: 2061

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

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

Upvotes: 1

Views: 11050

Answers (3)

kiwipom
kiwipom

Reputation: 7709

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")

Upvotes: 3

Tim B
Tim B

Reputation: 118

Why not just cast the SelectedItem to the type in your source collection?

MessageBox.Show(DirectCast(lstBox1.SelectedItem, MyType).Description.ToString, "Source Description")

Upvotes: 1

Tom Dudfield
Tom Dudfield

Reputation: 3107

I'm not to familiar with VB.NET but can you cast lstBox1.SelectedItem to the type that you are expecting and then get the description straight from that.

Dim foo As Foo = TryCast(lstBox1.SelectedItem, Foo)

If foo IsNot Nothing Then
    MessageBox.Show(foo.Dsecription, "Source Description")
End If

Upvotes: 0

Related Questions