c# - 如何根据其值更改 WPF 数据网格中单元格的背景颜色

标签 c# wpf xaml datagrid

我想根据 ist 值更改 wpf 数据网格中单元格的背景。我的数据网格如下:

<DataGrid x:Name="dataGridView_Comparison" ItemsSource="{Binding}" HorizontalAlignment="Stretch"    AlternatingRowBackground="LightBlue" AlternationCount="2"  Height="537" Margin="15,48,5,0" VerticalAlignment="Top" Width="1016" Background="#FF2C2727" Grid.ColumnSpan="2" Style="{DynamicResource DGHeaderStyle}" selectionUnit="FullRow">

我在 C# 中动态创建这个数据网格,因为列数总是根据输入而变化。执行此操作的代码部分是:

DataTable table = new DataTable();
        table.Columns.Add("Column1", typeof(string));
        foreach (string num in numbersList)
        {
            table.Columns.Add(num, typeof(string)); //Adding each numbers as a column in the table
        }
        foreach (string tc in uniqueCases)
        {
            DataRow newRow = table.NewRow(); 

            newRow["Column1"] = tc+"_Case"; //Adding the case name of the row
            foreach (string num in numbersList)
            {
                //For each number column add value corresponding to the condition..
                newRow[num] = "0"; //Default value as 0
                if (list_beforeThreshold.ContainsKey(num + tc) == true)
                {
                    newRow[num] = "1";
                }
                if (list_afterThreshold.ContainsKey(num + tc) == true)
                {
                    newRow[num] = "2";
                }
            table.Rows.Add(newRow);
        }

dataGridView_Comparison.DataContext = table.DefaultView;//添加到wpf中的datagrid

我是 c# 和 wpf 的新手。有人可以指导我如何根据单元格的值 (0,1,2) 为单元格赋予不同的颜色。 PS:我现在正在尝试数据触发。但没有取得任何进展。

编辑 1:列数和列名不能在 xaml 中硬编码,因为它们是在 C# 中动态填充的。

提前致谢

最佳答案

DataTrigger 应用于 DataGrid 中的所有单元格。当满足条件时,触发器将改变颜色,当不满足条件时,它会变回颜色。

<DataGrid>
    <DataGrid.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Property}"
                             Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

关于c# - 如何根据其值更改 WPF 数据网格中单元格的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038194/

相关文章:

c# - 用文本替换损坏的图像图标

c# - 具有多个日期字段的项目的订单集合

c# - WPF C# - 窗口 Chrome 调整重叠按钮的大小

WPF : Is it possible to adapt a path size to the layout size, 但还在拉伸(stretch)呢?

c# - 在 ObservableCollection 上使用 CollectionViewSource 进行列表框实时排序

c# - 相当于 foreach 的 XAML

c# - 有没有更好的方法来过滤可以传递给继承类的构造函数的对象类型?

c# - 如何在游戏中拥有局部位置和全局位置

c# - 以编程方式绑定(bind) DataGridTemplateColumn

c# - 如何创建和初始化自定义 Xamarin Forms 控件