I have a WPF DataGrid with some data. You can add rows through a separate window. The DataContext is the same, a LINQ-to-SQL object. Binding is also the same, I bind the \"I
The problem is that you need to refresh your LINQ-to-SQL DataContext. The DataContext's won't properly recognize the new row even after a submit changes. You need to dispose the DataContext you have and create a new one. In most cases DataContext should be used for one short operation and not as a long standing object.
For some reason Items.Refresh()
is not working for me.
What did work was to make my underlying collection inherit ObservableCollection
and then call its Add
method.
((ContactUIObjects)dgrdContacts.ItemsSource).Add(new ContactUIObject(o));
ContactUIObjects
is just the grids underlying collection.
I ran into same problem and found that best place for ObservableCollection is DataContext. It has some partial methods generated by designer that can be used to update collection. This code works pretty well:
partial class DataClassesDataContext
{
private ObservableCollection<Task> taskCollection;
public ReadOnlyObservableCollection<Task> TaskView { get; private set; }
partial void OnCreated()
{
taskCollection = new ObservableCollection<Task>(Tasks);
TaskView = new ReadOnlyObservableCollection<Task>(taskCollection);
}
partial void InsertTask(Task instance)
{
taskCollection.Add(instance);
this.ExecuteDynamicInsert(instance);
}
partial void DeleteTask(Task instance)
{
taskCollection.Remove(instance);
this.ExecuteDynamicDelete(instance);
}
}
If you have a case when you have to reload a grid in another window , you can simply close that window and invoke it again.
The reason it's not updating is that LINQ-to-SQL doesn't implement INotifyCollectionChanged, so WPF has no way to tell that the ItemsSource has been updated. The least terrifying way to fix this, is to copy your LINQ-to-SQL results to an ObservableCollection - when you do the Insert, also add to the observable collection. Then you'll see the update.
Or just invoke the search code again (usually the search button)> I have solved it in my case like this.