Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get indices of selected items in WPF's listbox?

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?

like image 754
Spook Avatar asked May 22 '13 10:05

Spook


2 Answers

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

like image 78
Dan Puzey Avatar answered Nov 10 '22 09:11

Dan Puzey


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));
like image 40
Sayse Avatar answered Nov 10 '22 07:11

Sayse