4

I'm creating a download manager, and my WPF DataGrid is bound to a collection of objects representing ongoing downloads (in separate threads). When I have multiple downloads running, each one is using this code to update its DataGrid item every second:

if (DateTime.Now > download.LastUpdateTime.AddSeconds(1))
{
    this.downloadsGrid.Items.Refresh();
    download.LastUpdateTime = DateTime.Now;
}

Datagrid.Items.Refresh() does the job, but it reconstructs the whole DataGrid , causing all downloads to update each others DataGrid rows several times in one second, and I don't want that kind of behavior. Is there any way to refresh a specific row (item) in a DataGrid?

Toni
  • 1,555
  • 4
  • 15
  • 23
marko
  • 217
  • 1
  • 4
  • 14
  • To 'update' single row without refreshing the entire UI https://stackoverflow.com/questions/11324688/how-to-refresh-datagrid-in-wpf/74770140#74770140 – Kamil Pająk Dec 12 '22 at 11:57

2 Answers2

9

If you bind your DataGrid to an ObservableCollection (which implements INotifyCollectionChanged) your DataGrid will be notified when a new item is added or an item is remove. Additionally, if you're just updating a property on an object in the collection the object should implement INotifyPropertyChanged and raise the PropertyChanged event which will tell the DataGrid to just update that value.

Dan Busha
  • 3,723
  • 28
  • 36
  • Thank you shriek and Dan Busha. I have a List, but I'm going to switch to ObservableCollection and implement INotifyPropertyChanged on WebDownloadClient by calling PropertyChanged event handler each second to update the datagrid. – marko May 08 '12 at 12:47
  • What if you want to change the background color depending on the state of the item in observable collection? – Stefan Vasiljevic Sep 13 '14 at 02:24
  • You'll need to modify the DataRow's style and bind the background value to a Brush property on your row item in the ObservableCollection – Dan Busha Sep 15 '14 at 16:28
8

Does your download class implement INotifyPropertyChanged? If not, that's why you have to call refresh to see a change in the grid. If you implement INotifyPropertyChanged the binding will be updated when the value is changed.

shriek
  • 5,157
  • 2
  • 36
  • 42