根据值条件更改 DataGrid 单元格颜色,如果为 0,则应显示灰色,否则使用 MVVM WPF 为黄色

问题描述 投票:0回答:1

我正在尝试使用 MVVM WPF 设计将表格绑定到网格后应用单元格背景颜色,我需要以下格式的输出(如附件所示)。

在将每个单元格绑定到网格视图之前,我尝试为每个单元格应用背景颜色

下面是我的 DataGrid 代码

                     CollectionViewSource collectionView = new CollectionViewSource();
                     collectionView.Source = dtStatus;
                     DataTable newDt = SetBackgroundColor(dtStatus);
                     WorkFlowGridCollectionView = newDt;  

我尝试了设置 YourBackgroundColorProperty 的方法:

    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(); /
                }                  
            }
        }
    }
wpf mvvm datagrid
1个回答
0
投票

向每列的每个

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>
© www.soinside.com 2019 - 2024. All rights reserved.