I’m struggling for quite some time now with binding my ListView to a table. I’ve read various solutions, but I keep running into trouble.
I have 2 database tables: Customers and Products. For each Customer there is a list of Products.
In my first attempt I bind to the generated Linq-to-SQL code. That means I binding immediately to Customer.Products. But since this is of type System.Data.Linq.EntitySet<Product>, I don’t get notified when items are added to/removed from the database.
So I extended the generated code by adding a method to Customer that wraps the returned System.Data.Linq.EntitySet<Product> in an ObservableCollection (as adviced by various blogs)
public ObservableCollection<Product> ObservableProducts
{
get
{
return new ObservableCollection<Product>(Products);
}
}
But now I cannot add anything to the collection. When I call ObservableProducts.Add() nothing is added..
An
ObservableCollectionis not a view on an underlying collection – it is a collection in its own right. When you pass theListto theObservableCollection, the items in theListare copied to theObservableCollection.So your item is being added, but only to the
ObservableCollection– not the underlyingListyou passed to it.Options for moving forward include:
ObservableCollectionin your data layer. Convert the entity list to anObservableCollectionstraight away and use that throughout the application.ObservableCollectionand applying those changes to the underlyingList.INotifyCollectionChangedthat is a view on an underlying collection. This can only work one-way (OC->List but not List->OC) and gets tricky if you have a multithreaded application.