【问题标题】:How to get indices of multiple item that were selected in listbox如何获取在列表框中选择的多个项目的索引
【发布时间】:2011-09-14 07:14:27
【问题描述】:

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

listbox.SelectedItems

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

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

【问题讨论】:

    标签: wpf silverlight windows-phone-7 listbox


    【解决方案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);
    

    【讨论】:

    • 如果同一个元素在列表中出现两次怎么办?
    • 如果 'MyObject' 是字符串并且您有重复项,则 IndefOf 不起作用。
    【解决方案2】:

    如果您要将 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 );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 2021-11-26
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      相关资源
      最近更新 更多