2016-09-01 67 views
0

我已經創建了一個WPF應用程序,它使用SqlClient DataTables中的數據加載2個DataGrid。我有下面的方法比較兩個表。它工作正常,但我必須在代碼中改變了一些破壞它的東西。現在dataGridRow1和dataGridRow2變量總是爲空。我如何從DataRowView中獲取DataGridRow?相反grid.ItemContainerGenerator.ContainerFromItem的如何從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

也許無論是用'DataGrid1.ItemContainerGenerator.ContainerFromItem'爲null,或者不是一個'DataGridRow'其他的東西回來。我會檢查該方法返回的內容。 –

+0

是的,ContainerFromItem返回null。我的問題是我還能做些什麼來獲得DataGridRow? –

回答

0

,請使用grid.ItemContainerGenerator.ContainerFromIndex功能,因爲Datadrid使用虛擬化,以便項目沒有在那個時候產生的。

+0

謝謝,我試過ContainerFromIndex,但它仍然返回null。 –

相關問題