我创建了一个WPF应用程序,它使用来自SqlClient DataTables的数据加载2个DataGrids。我有下面的方法比较两个表。它运行正常,但我必须在破坏它的代码中改变一些东西。现在dataGridRow1和dataGridRow2变量始终为null。如何从DataRowView获取DataGridRow?
private void CompareDataTables(string primaryKey)
{
foreach (DataRowView dataRowView1 in DataGrid1.ItemsSource)
{
DataGridRow dataGridRow1 = DataGrid1.ItemContainerGenerator.ContainerFromItem(dataRowView1) as DataGridRow;
if (dataGridRow1 != null)
{
int primaryKeyValue1 = (int)dataRowView1.Row[primaryKey];
foreach (DataRowView dataRowView2 in DataGrid2.ItemsSource)
{
//DataRowView dataRowView2 = (DataRowView)dataGridRow2.Item;
int primaryKeyValue2 = (int)dataRowView2.Row[primaryKey];
if (primaryKeyValue1 == primaryKeyValue2)
{
foreach (DataGridColumn column in DataGrid1.Columns)
{
DataGridRow dataGridRow2 = DataGrid2.ItemContainerGenerator.ContainerFromItem(dataRowView2) as DataGridRow;
if (dataGridRow2 != null)
{
FrameworkElement frameworkElement1 = column.GetCellContent(dataGridRow1);
FrameworkElement frameworkElement2 = GetFrameworkElement(DataGrid2, dataGridRow2, (String)column.Header);
if (frameworkElement1 is TextBlock && frameworkElement2 is TextBlock)
{
TextBlock textBlock1 = frameworkElement1 as TextBlock;
TextBlock textBlock2 = frameworkElement2 as TextBlock;
if (textBlock1.Text != textBlock2.Text)
{
textBlock1.Background = Brushes.LightSalmon;
textBlock2.Background = Brushes.LightSalmon;
}
}
}
}
break;
}
}
}
}
}
答案 0 :(得分:0)
取代grid.ItemContainerGenerator.ContainerFromItem,请使用grid.ItemContainerGenerator.ContainerFromIndex函数,因为Datadrid正在使用虚拟化,因此当时不生成Item。
答案 1 :(得分:0)
这似乎解决了这个问题。将这行代码放在ContinerFromItem:
之前DataGrid1.UpdateLayout();
谁会猜到?这是我找到这个答案的另一个问题的链接: