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
Table<TEntity>does not implementINotifyCollectionChanged, so the binding manager does not get notified that the collection’s contents have changed.A few options for you:
ObservableCollectionthat 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 similarTable<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.Also see this SO question: How to refresh a WPF DataGrid?