How to get indices of multiple item that were selected in listbox

£可爱£侵袭症+ 提交于 2019-12-08 11:42:19

问题


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?


回答1:


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



回答2:


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 );
  }
}


来源:https://stackoverflow.com/questions/7412559/how-to-get-indices-of-multiple-item-that-were-selected-in-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!