ns12345
ns12345

Reputation: 3105

MVVM Light how to determinte which records changed

in MVVM Light, if I have a datagrid binded(2 way) to an obersvable collection, and when I finally hit update after editing couple records and adding new ones, how do I determine which ones have been added new and which ones have been edited. (I guess which have primary key id = 0 can still be flagged as new but how to check which were edited)

Is there an inbuilt property? or I have create a property to flag those records?

Thanks

Upvotes: 1

Views: 374

Answers (1)

aqwert
aqwert

Reputation: 10789

You can attach to the CollectionChanged event on the ObservableCollection to find that out.

private void MyCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if(e.Action == NotifyCollectionChangedAction.Add)
    { 
         //use e.NewItems for added items
    }
    else if(e.Action == otifyCollectionChangedAction.Remove)
    {
         //use e.OldItems for removed items
    }
    ...
 }

As for finding out which ones have been edited this does not act on the collection itself but on the entities within the collection. A good idea is to have a ViewModel/Model represent each row and implement INotifyPropertyChanged or have IsDirty property that you can check against.

So when an item gets added attach to some event that will alert you of any changes. (you can do this inside the above CollectionChanged handler or some method that creates the model for you).

model.PropertyChanged += ModelChanged;
...
private void ModelChanged(object sender, PropertyChangedEventArgs e)
{
    Model model = (Model)sender;
    //Record in your own way that model has changed.
}

Upvotes: 1

Related Questions