1

I have a WPF MVVM app that contains an editable DataGrid. I am subscribing the DG SelectedItem event to a property in my ViewModel. This works well for modifying existing records and saving the changes to the database.

However, how can I tell when a new row is being created? When I click on the new row in the DG, the SelectedItem event does not fire. After the new row is created and I click on an exisitng row, the SelectedItem event fires but the EntityState does NOT know a row was added. How can I add a new row to my DB within the DG? Or, is there a better way to accomplish this?

This is what I am currently doing:

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");
        }
}
Yael
  • 1,566
  • 3
  • 18
  • 25
Jerry
  • 6,357
  • 8
  • 35
  • 50

1 Answers1

2

This could be considered a duplicate of this: WPF DataGrid - Event for New Rows?

See if that helps you at all.

Community
  • 1
  • 1
Xcalibur37
  • 2,305
  • 1
  • 17
  • 20