在将每个单元格绑定到网格视图之前,我尝试为每个单元格应用背景颜色
下面是我的 DataGrid 代码
CollectionViewSource collectionView = new CollectionViewSource();
collectionView.Source = dtStatus;
DataTable newDt = SetBackgroundColor(dtStatus);
WorkFlowGridCollectionView = newDt;
private void SetBackgroundColor(DataTable dt)
{
DataTable ddtt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
for (int j = 1; j < dt.Columns.Count; j++)
{
string cell = row[j].ToString();
int cellValue = Convert.ToInt32(cell);
// Assuming you have some condition to check for background color change
if (cellValue > 0)
{
YourBackgroundColorProperty = Brushes.Yellow.ToString();
}
else
{
YourBackgroundColorProperty = Brushes.Gray.ToString(); /
}
}
}
}
向每列的每个
DataTrigger
添加 CellStyle
,如果 Background
的当前行中的相应列(在下面的示例中名为“YourColumn”)为 0,则将 Gray
设置为 DataTable
:
<Style TargetType="DataGridCell">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Foreground" Value="#00FF00"/>
<Setter Property="Background" Value="Yellow"/>
<Setter Property="FontWeight" Value="Bold"/>
<Style.Triggers>
<DataTrigger Binding="{Binding YourColumn}" Value="0">
<Setter Property="Background" Value="Gray"/>
</DataTrigger>
</Style.Triggers>
</Style>