What is the proper way to handle multiple datagrids in a tab control so that cells leave edit mode when the tabs are changed?

后端 未结 4 1090
旧时难觅i
旧时难觅i 2020-12-03 07:23

In wpf I setup a tab control that binds to a collection of objects each object has a data template with a data grid presenting the data. If I select a particular cell and p

4条回答
  •  时光取名叫无心
    2020-12-03 07:45

    I have managed to work around this issue by detecting when the user clicks on a TabItem and then committing edits on visible DataGrid in the TabControl. I'm assuming the user will expect their changes to still be there when they click back.

    Code snippet:

    // PreviewMouseDown event handler on the TabControl
    private void TabControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (IsUnderTabHeader(e.OriginalSource as DependencyObject))
            CommitTables(yourTabControl);
    }
    
    private bool IsUnderTabHeader(DependencyObject control)
    {
        if (control is TabItem)
            return true;
        DependencyObject parent = VisualTreeHelper.GetParent(control);
        if (parent == null)
            return false;
        return IsUnderTabHeader(parent);
    }
    
    private void CommitTables(DependencyObject control)
    {
        if (control is DataGrid)
        {
            DataGrid grid = control as DataGrid;
            grid.CommitEdit(DataGridEditingUnit.Row, true);
            return;
        }
        int childrenCount = VisualTreeHelper.GetChildrenCount(control);
        for (int childIndex = 0; childIndex < childrenCount; childIndex++)
            CommitTables(VisualTreeHelper.GetChild(control, childIndex));
    }
    

    This is in the code behind.

提交回复
热议问题