Reputation: 1070
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
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
Children
collectionChildren
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:
OnPropertyChanged
event as you do so, toggling IsDirty whenever a property is changed. After initialisation,...IsDirty
.OnPropertyChanged
event.Upvotes: 1