开发者

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

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开发者_C百科 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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜