WPF datagrid 'newitemplaceholderposition' is not allowed during a transaction begun by 'addnew'

前端 未结 5 782
夕颜
夕颜 2021-01-02 23:49

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

5条回答
  •  囚心锁ツ
    2021-01-02 23:52

    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.

提交回复
热议问题