2
votes

I'm having a rather strange problem while working with a ListBox on a WPF program. I've defined my ListBox SelectionMode as Single, but it appear that even if visually I cannot select multiples items, it happens in the code. As can be seen here : SelectionModeSingleWithMultipleSelected

When trying to do a workaround, I tried to use the function UnselectAll, it rather strangly still leave an item selected : UnselectAllStillSelected

And as a last gift, once multiple items have been selected, if I try to click on my unselected visualy, selected in the code, item my application crash with a System.ArgumentException (I suppose it tries to select my item, that's already selected in fact, so it crashes because of adding a perfect duplicate ?) ApplicationCrashOnListBoxClick

I looked into ListBox is selecting many items even in SelectionMode="Single" that had kindof the same problem, but in my case I cannot visually select multiples items, and my items are completly distinct so it doesn't really help.

I don't have any custom behavior on ListBox.Click that could mess with something ...

my ListBox.ItemsSource is bound to a list of Items. I will decrement the value of a property of the selected Item when calling useItem on it, but it is still the same item (I don't recreate it/remove it then add it again)

Where is my problem coming from ? How can I fix it ?

2
Is SelectedItems bound to anything in your xaml?HasaniH
is it possible that something else is adding items to that list?HasaniH
I'm modifying the selected item in the 'useItem' function (my item posses an int charge field that I decrease by 1). But I only modify the item, I do not create a new one.Belterius

2 Answers

5
votes

So, finally found the origin of my problem.

Having a custom Item, I had to redefine my Equals function. I then had to redefine my GetHashCode function too, which I based on several of my properties, including the field I am decrementing ...
So when I would change the field, I would at the same time change my HashCode and I couldn't access my item anymore.

Changing my GetHashCode function to base it on an immutable field solved my problem.

1
votes

If your SelectionMode is Single, you should not bind to SelectedItems as per documentation. Just use SelectedItem.