views:

220

answers:

4

Hello,

I have a strange "problem". Could someone explain me why :

If I have in an ObservableCollection, twice (or more time) an item with the same value, then the selections of those values in the ListBox won't work properly ?

In fact, what the ListBox is doing when I click on an item(Even in single item selection) : It selects the first item from the ObservableCollection collection with a matching value. so in the case if multiple items with same value are in the collection, then only the first one will be selected !

A: 

You need to create a new object to hold each object.

I.e.

MyCollection.Add(new MyContainer() { Data = myObject } );

This way the listbox will select the objects properly as it has unique containers.

This would be implicit if you were using ViewModels

Chris
+2  A: 

Because objects you entered to collection have same references. you should create new instances in each case or override Equal function and write your logic for identifying items. WPF ListBox calls Object.Equal function to identify if the items are same.

Hope this helps

ArsenMkrt
A: 

Tx for the quick answer. I didn't know that the listbox was working this way. In fact the objects in the ObservableCollection are derived form Nhibernate poco object. I wanted the avoid a roundtrip to the DB for each object to get the "Id" of the object, but instead doing them all at the same time.

Indeed the newly created object have their id set to 0. It means for Nhibernate : "This object" needs to be inserted in the db to get the DB autoid.

Tx you for your help.

Fabian