I want to get indices of all the items that are selected in given listbox, there is a SelectedItems
method which return a collection of items:
listbox.SelectedItems
But there is no SelectedIndices
method. The collection also doesn't contain an index for each item.
How can I know which item was selected in my listbox?
You can simply use IndexOf
to find their index in the collection of items. For example, when binding a collection of items:
// create your list of items to display
List<MyObject> items = new List<MyObject>();
// NOTE: populate your list here!
// bind the items
listBox.ItemsSource = items;
You can find the selected index as follows:
var selectedItem = (MyObject)listBox.SelectedItems[0]
int index = items.IndexOf(selectedItem);
If you're binding a List
or an ObservableCollection
of items to the ListBox
use
var indices = new List<Int32>();
foreach( var item in listbox.SelectedItems ) {
var index = boundList.IndexOf( item as MyDataType );
if( index != -1 ) {
indices.Add( index );
}
}