【问题标题】:DataGrid's New Row Disappears if Editing and Switching Tabs on TabControl如果在 TabControl 上编辑和切换选项卡,DataGrid 的新行会消失
【发布时间】:2012-02-11 00:42:00
【问题描述】:
我的应用程序中有一个通过 XAML 创建的 WPF TabControl 对象。同样通过 XAML 创建的是一个包含 DataGrid 的 TabItem。在我的应用程序中,用户可以为该 TabControl 创建新的选项卡。发生这种情况时,将为该新 TabItem 创建一个 DataGrid。所以应用程序最终可能会包含多个带有 DataGrid 的 TabItem,即使我只通过 XAML 创建了一个带有 DataGrid 的 TabItem。
我看到一个问题,如果用户想要在 DataGrid 中添加新行,但随后决定切换到不同的选项卡,则当用户返回到该选项卡时,DataGrid 会丢失新行。因此,不可能向 DataGrid 添加新行。奇怪的是,这个问题只发生在为动态 TabItems 动态创建的 DataGrids 上。因此,通过 XAML 创建的 DataGrid 中不存在此问题。有人见过这个问题吗?
【问题讨论】:
标签:
c#
wpf
datagrid
tabcontrol
tabitem
【解决方案1】:
看来您需要在更改选项卡之前在网格中提交所有编辑。这是一个很好的解决方法,我发现它非常有用:
// 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));
}