C# 数据网格&x27;如果在TabControl上编辑和切换选项卡,则s新行将消失

C# 数据网格&x27;如果在TabControl上编辑和切换选项卡,则s新行将消失,c#,wpf,datagrid,tabcontrol,tabitem,C#,Wpf,Datagrid,Tabcontrol,Tabitem,我的应用程序中有一个通过XAML创建的WPF TabControl对象。还通过XAML创建了一个包含DataGrid的TabItem。在我的应用程序中,用户可以为该选项卡控件创建新选项卡。发生这种情况时,将为该新选项卡项创建一个数据网格。因此,应用程序可能最终包含多个带有DataGrid的TabItems,即使我通过XAML只创建了一个带有DataGrid的TabItem 我发现一个问题,如果用户想在DataGrid中添加新行,但又决定切换到其他选项卡,那么当用户返回到该选项卡时,DataGri

我的应用程序中有一个通过XAML创建的WPF TabControl对象。还通过XAML创建了一个包含DataGrid的TabItem。在我的应用程序中,用户可以为该选项卡控件创建新选项卡。发生这种情况时,将为该新选项卡项创建一个数据网格。因此,应用程序可能最终包含多个带有DataGrid的TabItems,即使我通过XAML只创建了一个带有DataGrid的TabItem


我发现一个问题,如果用户想在DataGrid中添加新行,但又决定切换到其他选项卡,那么当用户返回到该选项卡时,DataGrid将丢失新行。因此,不可能向DataGrid添加新行。奇怪的是,这个问题只发生在为动态TabItems动态创建的数据网格上。因此,通过XAML创建的DataGrid中不存在此问题。以前有人看到过这个问题吗?

事实证明,在堆栈溢出问题上,有一个问题与此问题非常相似。这里有一个链接。公认的答案就是为我解决问题的答案


在更改选项卡之前,您似乎需要提交网格中的所有编辑。以下是我发现非常有用的一个很好的解决方法:

// 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));
}
//选项卡控件上的PreviewMouseDown事件处理程序
私有无效选项卡控件_PreviewMouseDown(对象发送器,鼠标按钮ventargs e)
{
if(IsUnderTabHeader(例如,OriginalSource作为DependencyObject))
委托书(控制);
}
private bool IsUnderTabHeader(DependencyObject控件)
{
if(控件为TabItem)
返回true;
DependencyObject parent=VisualTreeHelper.GetParent(控件);
如果(父项==null)
返回false;
返回在选项卡标题下(父级);
}
私有无效提交文件(DependencyObject控件)
{
if(控件为DataGrid)
{
DataGrid=控制为DataGrid;
committedit(DataGridEditingUnit.Row,true);
返回;
}
int childrenCount=visualtreeheloper.GetChildrenCount(控件);
对于(int childIndex=0;childIndex