Reputation: 3407
I am building a WPF app where a DataGrid
binds a HashSet
of Product
, and two Products
with the same ID are considered equal. A user is allowed to add new row to the DataGrid
to describe a new Product, and I'd like to notify the user if two rows have the same ID. But how do I detect that? The problem is that the DataGrid
binds to items
, which was created as
items = new ObservableCollection<Product>(new HashSet<Product>());
and the duplicate product is automatically inserted and never ends up in the items
(although it does show up on the DataGrid
, why?)
so in short, 2 questions:
Upvotes: 0
Views: 219
Reputation: 27338
Let me explain first, why this new ObservableCollection<Product>(new HashSet<Product>());
does not work.
ObservableCollection is not wrapper of other collection like hashset. Your code baiscaly creates hashset, whose items are then copied to ObservableCollection. the hashset is then lost (garbage collected) since there is no reference to it. Nothing prevents from inserting duplicate IDs.
How to detect the duplicate at the time of insertion?
If possible, don't let user to edit ID, but autogenerate it for him. Otherwise you need to listen to collectionchanged of products collection to ensure uniqueness at the time of insertion and propertychanged event of each product to enqure uniqueness if ID is edited.
Another option is to create your own class inherited from ObservableCollection and override InsertItems and SetItems methods
Upvotes: 1