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

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

本文介绍了如何获取在列表框中选择的多个项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

您可以简单地使用IndexOf在项目集合中找到它们的索引.例如,在绑定项目集合时:

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

这篇关于如何获取在列表框中选择的多个项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:40