bdristan
bdristan

Reputation: 1070

How to notify parent view model of datagrid changes using MVVM?

I have read quite a number of posts on this site about handling of changes in datagrid. The general consensus seems to be that datagrid items should implement INotifyPropertyChanged and then do whatever necessary in OnPropertyChanged(). However I'm not quite clear what a recommended practice is when view model and model are taken into account.

Let's say that my model has many fields and mulitiple lists of items of different type. The lists of items are bound as ItemSource to datagrids in a corresponding view. In my view model (or model) I'd like to have a flag (e.g. 'IsDirty') that tells me if anything was changed in fields and/or in items of the lists.

Handling changes made to fields is simple because their corresponding OnPropertyChanged() will be called in the view model. However, datagrid items' OnPropertyChanged() will be called in items themselves.

How do I let the parent view model (or model) know that a change was made to one of the items in one of the datagrids? Obviously I could give each item a reference to its parent view model (or model) but I wonder if there is a better and recommended practice.

Thanks.

Upvotes: 0

Views: 1132

Answers (1)

Barracoder
Barracoder

Reputation: 3764

Maintaining a parent IsDirty property can most simply be accomplished through listening to child items' OnPropertyChanged events, combined with the use of ObservableCollections and the CollectionChanged event.

There are normally only three use cases

  1. Child item property is updated
  2. Child item is added to the Children collection
  3. Child item is deleted from the Children collection.

The simplest solution is to create a Children property of type ObservableCollection<Child> and hook into the CollectionChanged event. This event fires whenever a Child is added or removed from the collection. In this event you can capture all the data that you need:

  1. On Parent initialisation, add all the initial children to the collection, hooking into each one's OnPropertyChanged event as you do so, toggling IsDirty whenever a property is changed. After initialisation,...
  2. Child added - hook into the child's OnPropertyChanged event and toggle IsDirty.
  3. Child deleted - de-hook from the Child's OnPropertyChanged event.

Upvotes: 1

Related Questions