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
I have used holmes answer but didn't work for me properly. So I changed little bit.
Here is my solution:
First of all, because of I'm using MVVM, I added this codes to the datagrid:
Namespaces are these:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Then, I added this code to the ViewModel and set the DataGrid:
private DataGrid _dg { get; set; }
public void OnDataGridInitializingNewItem(object sender, InitializingNewItemEventArgs e)
{
if (_dg == null)
_dg = (DataGrid)sender;
}
After all, when needed, I ran this code:
_dg.CommitEdit();
Finally it works very well :)
PS: First, I had tried CancelEdit method instead of CommitEdit. It worked and I went to another view that opened like pop-up. When I finished what to do and return to the view, last added row was gone. But it was committed to the db. After re-open the view, it was there.