如何获取在列表框中选择的多个项目的索引

时间:2011-09-14 07:14:27

标签: wpf silverlight windows-phone-7 listbox

我想获取在给定列表框中选择的所有项目的索引,有一个SelectedItems方法返回一组项目:

listbox.SelectedItems

但是没有SelectedIndices方法。该集合也不包含每个项目的索引。

如何知道我的列表框中选择了哪个项目?

2 个答案:

答案 0 :(得分:1)

如果您将ListObservableCollection个项目绑定到ListBox使用

var indices = new List<Int32>();
foreach( var item in listbox.SelectedItems ) {
  var index = boundList.IndexOf( item as MyDataType );

  if( index != -1 ) {
    indices.Add( index );
  }
}

答案 1 :(得分:1)

您只需使用IndexOf在项目集合中查找其索引即可。例如,绑定项目集合时:

// create your list of items to display
List<MyObject> items = new List<MyObject>();

// NOTE: populate your list here!

// bind the items
listBox.ItemsSource = items;

您可以按如下方式找到所选索引:

var selectedItem = (MyObject)listBox.SelectedItems[0]
int index = items.IndexOf(selectedItem);