我在我的視圖模型中動態創建兩個數據表。 在我將它們顯示在視圖中之前,我將一個DataTable中的每個單元格值與第二個DataTable中的同一個單元格進行比較。 我的問題是我想提供不同的單元格不同的背景顏色。我怎樣才能做到這一點?MVVM WPF動態數據網格
這裏是第一個DataGrid:
<GroupBox Header="Xml 1 Details" Margin="10,10,10,10" Grid.Row="1" Grid.ColumnSpan="4" Grid.Column="0">
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<GroupBox x:Name="GridGroupBox"
Grid.Column="0"
Header="{Binding TableName}">
<DataGrid x:Name="DataGrid" Margin="5,5,5,5"
ItemsSource="{Binding GenericDataTable}"
attachedBehaviors:DataGridColumnsBehavior.BindableColumns="{Binding GridColumns}"
AutoGenerateColumns="False"
EnableRowVirtualization="False">
</DataGrid>
</GroupBox>
</Grid>
</ScrollViewer>
</GroupBox>
第二個DataGrid:
<GroupBox Header="Xml 2 Details" Margin="10,20,10,10" Grid.Row="2" Grid.ColumnSpan="4" Grid.Column="0">
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<GroupBox x:Name="GridGroupBox2"
Grid.Column="0"
Header="{Binding TableName}">
<DataGrid x:Name="DataGrid2" Margin="5,5,5,5"
ItemsSource="{Binding GenericDataTable2}"
attachedBehaviors:DataGridColumnsBehavior.BindableColumns="{Binding GridColumns2}"
AutoGenerateColumns="False"
EnableRowVirtualization="False"
/>
</GroupBox>
</Grid>
</ScrollViewer>
</GroupBox>
編程創建他們:
private void GenerateFirstXmlDynamicColumns(DataTable dt, List<string> cols)
{
GridColumns = new ObservableCollection<DataGridColumn>();
foreach (DataColumn col in dt.Columns)
{
GridColumns.Add(new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(col.ColumnName)
});
}
RaisePropertyChanged("GridColumns");
GenericDataTable = dt;
RaisePropertyChanged("GenericDataTable");
}
private void GenerateSecondXmlDynamicColumns(DataTable dt, List<string> cols)
{
GridColumns2 = new ObservableCollection<DataGridColumn>();
foreach (DataColumn col in dt.Columns)
{
GridColumns2.Add(new DataGridTextColumn
{
Header = col.ColumnName,
Binding = new Binding(col.ColumnName)
});
}
RaisePropertyChanged("GridColumns2");
GenericDataTable2 = dt;
RaisePropertyChanged("GenericDataTable2");
}
在這裏,我比較細胞,我想改變不同單元的背景顏色:
private void CompareData()
{
for (int i = 0; i < GenericDataTable.Rows.Count; i++)
{
for (int j = 0; j < GenericDataTable.Columns.Count; j++)
{
if (!GenericDataTable.Rows[i][j].Equals(GenericDataTable2.Rows[i][j]))//if cells are different
{
}
}
}
}
獲得幫助這裏的方法是嘗試第一,顯示你的代碼,然後人都樂於幫助。 – kenny