0

I have an ObservableCollection defined as follows

private ObservableCollection<RelayConfig> _relayConfigs;
public ObservableCollection<RelayConfig> RelayConfigs { 
    get {return  _relayConfigs;}
    set { _relayConfigs = value; }
}

This is bound to wpf Datagrid using ItemsSource attribute and populated as given below

RelayConfigs = new ObservableCollection<RelayConfig>(unitOfWork.RelayConfigRepository.GetQueryable().Include(rc => rc.StandardContacts));

I am removing items from ObservableCollection that matches a specific criteria like this.

RelayConfigs.RemoveWhere(r => r.IsMarked);

RemoveWhere is an Extension method for ObservableCollection, defined like this

public static void RemoveWhere<T>(this ICollection<T> collection, Func<T, bool> predicate) {
    var i = collection.Count;
    while (i-- > 0) {
        var element = collection.ElementAt(i);
        if (predicate(element)) {
            collection.Remove(element);
        }
    }
}

The issue is that when I remove some rows from the ObservableCollection using the above setup, I don't see the DataGrid getting refreshed. The rows still linger around in the DataGrid, when infact it does not exist in the ObservableCollection. Any ideas why Datagrid does not get refreshed.

Jatin
  • 4,023
  • 10
  • 60
  • 107
  • Just check this on another ItemsControl to be sure it is (or not) DataGrid to blame. By the way I prefer not to use setters for collections making the field readonly. It's easy to change the reference later but the old binding will be left with not actual reference. – Pavel Voronin Nov 19 '12 at 05:12
  • I don't think there is issue is with Datagrid. I have code, very similar to what I have posted here, for another entity which is working fine. Its just not working in this case only. By the way, I will follow your suggestion to make Collections readonly. Sounds logical. – Jatin Nov 19 '12 at 05:34
  • There's only one trouble with observable collection in WPF. If you want totally refill it with new items you have to delete and add items one by one causing update on each operation. That's why many prefer to change the very collection and to raise PropertyChanged event in the setter. To overcome this shortcoming I just coded my own collection ListWithNotifications : INotifyCollectionChanged If you need I can share the source here. – Pavel Voronin Nov 19 '12 at 06:33

1 Answers1

0

I've run into that exact same thing, even with applying changes to row values. The solution I found was very simple otherwise...

YourDataGrid.Items.Refresh();

It tell your datagrid to go back to whatever source has the items its displaying and refresh them with whatever the latest values are. This way, no "binding" is lost, just the refresh as you would expect.

DRapp
  • 47,638
  • 12
  • 72
  • 142
  • Actually, I am using MVVM (Caliburn Micro) and I don't have a reference of DataGrid in my ViewModel. So your solution could not be realized in my case. – Jatin Nov 19 '12 at 02:49