user2023861
user2023861

Reputation: 8208

Why is my DataGrid with a ObservableCollection<T> apparently not refreshing when I add or remove items from the collection?

I'm having a problem with a DataGrid and its underlying ObservableCollection. I want to add and remove rows programmatically from the collection and have the results appear in the DataGrid. While I expect that this will automagically happen for me, it doesn't. I've found that if I sort the data afterwards, that the rows will appear as I want them. Here's what I do:

  1. DataGrid's ItemsSource is set to my ObservableCollection<T>.

  2. User clicks button that fires an ICommand that removes rows with a value of X.

  3. What the user sees looks exactly the same: no rows are removed.

  4. User clicks column header to sort the DataGrid. Now the rows are removed.

What's going on here? The rows that I want removed, stay until I sort the columns. I found out something else as well. If I refresh the DataGrid.Items, the rows are removed. That code is simply:

this.dg.Items.Refresh();  //"dg" is my DataGrid

While this is not very MVVM, it works.

Upvotes: 1

Views: 140

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

Make sure you're binding directly to your ObservableCollection, e.g., you are not tacking on any Linq operators, wrapping it in a collection view/proxy, etc. Any transformation/wrapper on your collection that does not forward collection change events will prevent the grid from being notified of changes.

Upvotes: 3

Related Questions