I have a tabControl on a WPF form.
In one of the Tab Items I have a User Control that contains a DataGrid which has CanUserAddRows="True"
. The user can type data in the column and when they press [enter], a new row is created.
The problem is when I type data into the new row and then change tabs I get this exception: "WPF datagrid 'newitemplaceholderposition' is not allowed during a transaction begun by 'Addnew' "
Any suggestions how to avoid it?
I have tried to put dg.CommitEdit()
on usercontrol.Unloaded()
. I don't get the exception, but I also don't get the new row.
I ran into the same problem...here are some snippets describing how I solved it. Note that in my case I wanted to reject the changes to avoid the error. If you want to commit the changes, this may lead you in the right direction.
1a) Use the InitializingNewItem event on the datagrid to capture the adding row.
private void mydatagrid_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
{
_viewmodel.NewRowDefaults((DataRowView)e.NewItem);
}
1b) In this case, I'm calling a method in my view model to populate row defaults and save a reference to the row.
private DataRowView _drvAddingRow { get; set; }
public void NewRowDefaults(DataRowView drv)
{
_drvAddingRow = drv;
...
}
2) Then when you need to reject the change (before notifying property changes or whatever your case is), use the CancelEdit method on the captured datarowview.
_drvAddingRow.CancelEdit();
I just ran into the same problem. Found two possible workarounds:
1/ Trigger the CommitEdit event of the DataGrid, then call CommitEdit. I'm not sure why this last step is needed, you may not have to call CommitEdit in your case.
DataGrid.CommitEditCommand.Execute(this.DataGridWorkItems, this.DataGridWorkItems);
yourDataGrid.CommitEdit(DataGridEditingUnit.Row, false);
2/ Simulate a stroke on the 'Return' key of the keyboard:
var keyEventArgs = new KeyEventArgs(InputManager.Current.PrimaryKeyboardDevice,PresentationSource.FromDependencyObject(yourDataGrid), System.Environment.ProcessorCount, Key.Return);
keyEventArgs.RoutedEvent = UIElement.KeyDownEvent;
yourDataGrid.RaiseEvent(keyEventArgs);
I settled for the last solution, since I had a few fishy side effects with the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With