tags:

views:

582

answers:

1

Hi all,

I'm struggeling 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, 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 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..

+2  A: 

An ObservableCollection is not a view on an underlying collection - it is a collection in its own right. When you pass the List to the ObservableCollection, the items in the List are copied to the ObservableCollection.

So your item is being added, but only to the ObservableCollection - not the underlying List you passed to it.

Options for moving forward include:

  • Using an ObservableCollection in your data layer. Convert the entity list to an ObservableCollection straight away and use that throughout the application.
  • Listening for changes to the ObservableCollection and applying those changes to the underlying List.
  • Write an implementation of INotifyCollectionChanged that 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.

HTH, Kent

Kent Boogaart