1
votes

The code I am working on uses a WPF DataGrid to store a table of entries, bound to an ObservableCollection of items, with the possibility for the user to create new items using the blank row at the bottom of the table.

When the user selects a cell in the new row, right as they type their first keystroke, the DataGrid creates a new blank item and inserts it in the ObservableCollection. Once the user hits Enter or takes focus away from the cell, the new text is committed as an edit to the item.

Is there any way to change the behavior of the DataGrid so that it does not create a blank item before the user is done typing? Or, at least, does not add the blank item to the ObservableCollection until after the row is committed.

I'd like to make it so that new items are only added to the ObservableCollection after a full-row commit has occurred, meaning that each new item added to the Collection will already have data in it, instead of being inserted blank and then edited later.

I've searched high and low for an answer, but it appears that no one else is having this problem.

The reason why I want this functionality is that I am implementing an "Undo" feature in this DataGrid, but when new rows get added as blanks and then edited later, that always ends up counting as two changes, meaning the user needs to perform two "Undo" operations to remove a row they have just barely created. And that's not intuitive at all.

Thanks.

1
Also, we're software people here, so we read code faster than a novel like you posted here. Please provide a minimal reproducible example of your current setup.dymanoid
This is a largely conceptual question. I merely want to know if changing the behavior of the DataGrid is possible. The code in question is the code of the DataGrid class.PickenChoose

1 Answers

1
votes

In general it's normal behavior of DataGrid.

  1. DataGrid calls Add() for the new collection item when you start editing the row
  2. DataGrid automatically calls Remove() for the item when you hit Escape key or call CancelEdit() in any other way

There's nothing strange to support (ignore in code) collection items with blank/default values. As alternative you may add some proxy collection and commit its changes to main collection when Datagrid saves the Row data. As for me, first way is preferrable.