2

Here's the excerpt from https://learn.microsoft.com/en-us/archive/blogs/vinsibal/5-random-gotchas-with-the-wpf-datagrid:

5.Data source items should implement IEditableObject to get transactional editing functionality.

If you are not familiar with IEditableObject, see this MSDN article which has a good explanation and code sample. The DataGrid has baked in functionality for transactional editing via the IEditableObject interface. When you begin editing a cell, the DataGrid gets into cell editing mode as well as row editing mode. What this means is that you can cancel/commit cells as well as cancel/commit rows. For example, I edit cell 0 and press tab to the next cell. Cell 0 is committed when pressing tab. I start typing in cell 1 and realize I want to cancel the operation. I press ‘Esc’ which reverts cell 1. I now realize I want to cancel the whole operation so I press ‘Esc’ again and now cell 0 is reverted back to its original value.

I get this same transactional behavior even without implementing IEditableObject. What am I missing?

  public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Description { get; set; }
  }

  People = new List<Person> {
    new Person(){FirstName = "fname", LastName = "lname", Description = "description"}
  };

  <DataGrid ItemsSource="{Binding Path=People}" />
Mike Christiansen
  • 1,104
  • 2
  • 13
  • 30
alice
  • 2,547
  • 4
  • 24
  • 30

1 Answers1

2

Of course it doesn't matter that much for a simple string in memory. But there are uses for IEditableObject.
For example, imagine you want to store every edited record to a database. You probably would want to commit all changes in one transaction, which would be in EndEdit(). Similar uses can be found for the other interface methods.

Also, you are not always directly editing the bound object. Your IEditableObject instance might hold a variable of another type wich is the actual data source. You would not apply the edited values until EndEdit() was called in that case, and CancelEdit() would restore the values from the original data source.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • What if the database operation fails? I don't think EndEdit() is a good place to do a database operation. – alice Jun 05 '12 at 12:35
  • @alice Then you would have to handle the error accordingly. It doesn't have to be a database though, it can also be another in-memory object, or any other object that you don't want anyone to touch until the changes are final. Using a plain object with just a few string properties is not a good example for IEditableObject. – Botz3000 Jun 05 '12 at 12:56