Harald
Harald

Reputation: 1037

WPF DataGrid update on CollectionChanged fails

I have bound a DataGrid to an ObservableCollection of type TEntity. The collection holds Entity Framework entities.

When such an entity changes in the DB the app gets notified. In case it is a simple replace change I simply overwrite the entity in the ObservableCollection.

However, that does NOT trigger a UI refresh. I think the problem is that it is still the same object I am referring to. The entity is now definitely different (I do a reload on the DbContext) than what the UI shows because some columns have changed.

When I do this

collection[index] = changedObject;

Nothing happens. The collection correctly fires a CollectionChanged event but the UI does not update anything.

Then I tried this:

collection[index] = new TEntity();  // Create a dummy object
collection[index] = changedObject;

Now the UI updates but the collection of course fires 2 CollectionChanged events.

I guess one option would be to fire a PropertyChanged event for all properties of the changed entity but that seems overkill (way too many events) and so far I don't have a need to implement the event on my EF classes.

My question: How can I reliably update a WPF bound ObservableCollection if a row has changed but the object is still the same (although properties within the object have changed)?

Upvotes: 0

Views: 769

Answers (2)

Harald
Harald

Reputation: 1037

Just wanted to add some additional info to the answer from Chris Laffey, which is the correct answer.

Further reading revealed that the CollectionChanged event for a Replace action will not be processed by WPF if the old object and the new object are the same.

I had a particular nasty side effect in my app, where I was displaying EF entities in an ObservableCollection in WPF.

I was monitoring the DB for changes. When a table row got modified the entity got reloaded from the DbContext. Since the ObservableCollection used the same EF entity objects (at the same memory location) this caused an overwrite of the PropertChanged event, which is apparently reset when an entity is reloaded.

Upvotes: 0

BotBot
BotBot

Reputation: 26

You will have to use PropertyChanged for each property or use one PropertyChanged event to indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs. Documentation

Upvotes: 1

Related Questions