ListBox/Listview selection issue RRS feed

  • Question

  • I've recently noticed an issue (feature?) with ListBoxes/ListViews in WPF. It appears that if the underlying collection of items is of an object whose Equals() is overridden to use by value comparisons (such as strings), the selection mechanism fails to work as expected. What I am referring to specifically is the control's inability to select a single item if duplicates are found in the list. For example, if you create a ListBox and set its ItemsSource to a collection of the following strings: one, two, three, one, two; selection of either "one", or "two" results in the selection of its counterpart as well. Furthermore, the issue is only apparent when you click on a duplicate that is lower, i.e. one with a higher index within the collection.

    Is this by design? It appears as if aside from selecting just the item you click on, the control searches its underlying collection, comparing each item using its Equals(), and also selecting the first item it finds. If this is by design, it seems rather odd. Basically this means you cannot have a ListBox/ListView/any Selector derived class full of strings, or other Equals() overridden objects with duplicates because it completely breaks the selection. I noticed there was a post describing this issue and the solution was to write wrapper classes that override Equals() to do a by reference comparison. According to Microsoft guidelines, an override of Equals() should use a value comparison, and reference comparisons should use ReferenceEquals(). It's got to be more simple than that, one would think.

    Any input would be appreciated...
    Saturday, July 18, 2009 12:05 AM


All replies