How to get indices of selected items in a WPF list?

Before marking this question as a duplicate or suggesting using Items.IndexOf, follow these steps:

public MainWindow() { InitializeComponent(); var A = new object(); var B = new object(); var C = new object(); lbItems.Items.Add(A); lbItems.Items.Add(B); lbItems.Items.Add(C); lbItems.Items.Add(A); lbItems.Items.Add(B); lbItems.Items.Add(C); } private void lbItems_MouseDoubleClick(object sender, MouseButtonEventArgs e) { MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString()); } 

Then double-click the fourth element (you get 0 instead of 3).

How to get a list of indices of selected items?

+7
source share
2 answers

This is because you add the same object to the list twice. The ListBox control cannot determine between. One way to solve this problem is to wrap each element in a different class:

 lbItems.Items.Add(new WrappedThing((a)); lbItems.Items.Add(new WrappedThing((b)); lbItems.Items.Add(new WrappedThing((a)); lbItems.Items.Add(new WrappedThing((b)); 

... This means that each element in the list is unique, although the element that they wrap may not be. Note that any data template or binding would also need to be changed to support this, although you could do it with one global DataTemplate .

WrappedThing will look something like this:

 class WrappedThing<T> { public WrappedThing(T thing) { Thing = thing; } public T Thing { get; private set; } } 

(Note: this is copied from my answer to another question here , as the answer is useful, but the question is slightly different.)

+3
source

In addition to my comment ("getting it the first index of object A, which is 0"),

 int j = 0; for (int i = 0; i < lbItems.Items.Count; i++) { if (lbItems.Items[i] == lbItems.SelectedItems[0]) j++; } MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString() + string.Format("\r\nThere are {0} occurences of this object in this list", j)); 
+3
source

All Articles