Sunday, January 24, 2010

Refresh WPF DataGrid

I am using WPF DataGrid for displaying a list of items. I had to modify an item, but the item had no INotifyPropertyChanged event on that property (it was a collection).

So my first idea was:

  1. Update the list behind ItemsSource
  2. Set ItemsSource property to null to force unbinding
  3. Set ItemsSource property to the new collection
  4. Set the SelectedItem to the new item
  5. Call ScrollIntoView() on the new item

Well, I got a huge exception at step 5. There must be a simpler solution. And there is.

The DataGrid generates a view of the ItemsSource. All I have to do is call the Items.Refresh() method, and it will rebind to the ItemsSource. Everything will be rebound, all updates will be visible. Selected item kept, visibility kept.

3 comments:

  1. The method of items.Refresh to force an update of a WPF Datagrid is often repeated in the web, but doesn't actually work. If I had the answer I would repeat it here, but I am still looking for one.

    ReplyDelete
  2. This fixed it for me: http://stackoverflow.com/questions/2472680/refresh-datagrid-on-view-from-viewmodel/7603765#7603765

    ReplyDelete
  3. Great post, much appreciate the time you took to write this.

    ReplyDelete