【发布时间】:2011-09-14 07:14:27
【问题描述】:
我想获取在给定列表框中选择的所有项目的索引,有一个 SelectedItems 方法返回项目集合:
listbox.SelectedItems
但是没有SelectedIndices 方法。该集合也不包含每个项目的索引。
我如何知道在我的列表框中选择了哪个项目?
【问题讨论】:
标签: wpf silverlight windows-phone-7 listbox
我想获取在给定列表框中选择的所有项目的索引,有一个 SelectedItems 方法返回项目集合:
listbox.SelectedItems
但是没有SelectedIndices 方法。该集合也不包含每个项目的索引。
我如何知道在我的列表框中选择了哪个项目?
【问题讨论】:
标签: wpf silverlight windows-phone-7 listbox
您可以简单地使用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);
【讨论】:
如果您要将 List 或 ObservableCollection 的项目绑定到 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 );
}
}
【讨论】: