views:

39

answers:

1

Good afternoon,

I am trying to use as Linq to SQL datacontext for a ListBox in WPF.

Basically, I assign the Linq DataContext to the form's DataContext property. Then, I bind it to the list.ItemsSource.

Everything works fine, I can show the details of each of my elements in a textbox (master-details scheme).

The thing is, I would like to be able to add a new element to the list:

private void Button_Click(object sender, RoutedEventArgs e)
    {

        Button btn = sender as Button;

        var table = lst_markets.ItemsSource as System.Data.Linq.Table<Market>;
        table.InsertOnSubmit(new Market() { IdMarket = Guid.NewGuid(), Name = txt_newmarket.Text });
        table.Context.SubmitChanges();
    }

The value is indeed added to the database, but the ListBox is not refreshed.

What should I do to refresh the list?

Thanks,

Jeremie

A: 

Table<TEntity> does not implement INotifyCollectionChanged, so the binding manager does not get notified that the collection's contents have changed.

A few options for you:

  • keep an ObservableCollection that you fill from the table, and keep synchronized. As you add/remove items from it the list would stay synchronized via binding. See this article for something similar
  • Hack around it - set the lst_markets.ItemsSource to null and back to the table when changing the collection. This would cause a full rebind, and feels like a dirty hack, but should work.
  • Don't Do that! A Table<T> is not a collection - it represents a query. Bind to a collection instead. If I remember correctly, every time you iterate a Table it queries the database, which means that any time the listbox feels it needs to enumerate, or the binding manager, or your ui code does the same you are hitting the database.
  • This forum post has an ObservableEntitySetWrapper that may give you some ideas.

Also see this SO question: http://stackoverflow.com/questions/930350/how-to-refresh-a-wpf-datagrid

Philip Rieck
The observable collection using the CollectionChanged event is clearly the simplest way. Cheers
JSmaga