Before you mark this question as a duplicate or suggest using Items.IndexOf, please do the following:
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 doubleclick fourth element (you'll get 0 instead of 3).
How to get a list of selected item indices?
This is caused by you adding the same object to the list twice. The ListBox
control can't tell between them. One way around this problem is to wrap each item in another 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));
... which means that each item in the list is unique, even though the item they're wrapping may not be. Note that any data template or bindings would also have to change to support this, though you could do this with a single global DataTemplate
.
WrappedThing
would 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 a different question here since the answer is useful but the question is slightly different.)
Further to my comment (" its getting 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With