I have an MVVM WPF application that contains an editable DataGrid. I am signing a DG SelectedItem event on a property in my ViewModel. This works well to modify existing records and save changes to the database.
However, how can I determine when a new line is created? When I click on a new line in the DG, the SelectedItem event does not fire. After creating a new line and clicking on the exisitng line, the SelectedItem event is triggered, but the EntityState does NOT know that the line has been added. How to add a new row to my database in DG? Or is there a better way to do this?
This is what I am doing now:
Xaml:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ContactList}" SelectedItem="{Binding SelectedItemContact, UpdateSourceTrigger=PropertyChanged}" .....>
ViewModel:
public Contact SelectedItemContact { get { return _selectedItemContact; } set { if (value != _selectedItemContact) { bool changesMade = Repository.Context. ObjectStateManager. GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified ).Any(); if (changesMade) { Repository.Context.SaveChanges(); MessageBox.Show("Changes Saved!"); } _selectedItemContact = value; OnPropertyChanged("SelectedItemContact"); } }
source share