How to add rows with DataGrid and MVVM

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"); } } 
+1
source share
1 answer

This could be considered a duplicate of this: WPF DataGrid - an event for new rows?

See if this helps you at all.

+1
source

Source: https://habr.com/ru/post/958782/


All Articles