【问题标题】:How to change background color of a cell in WPF datagrid based on its value如何根据其值更改WPF数据网格中单元格的背景颜色
【发布时间】:2019-05-08 10:06:17
【问题描述】:

我想根据 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# 中动态填充的。

提前致谢

【问题讨论】:

  • 请参阅stackoverflow.com/q/5549617/1136211 和其他类似问题。
  • @Clemens 我已经尝试了大多数这些解决方案。他们没有解决我的问题,因为我的数据网格列不是静态的。由于我是 wpf 的新手,我不确定我是否遵循为我的数据网格构建数据表的正确方法

标签: c# wpf xaml datagrid


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    您可以使用IValueConverter来改变背景颜色。

    在 xaml 中定义 Converter 类:

    <Window.Resources>
        <local:NameToBrushConverter x:Key="NameToBrushConverter"/>
    </Window.Resources>
    <Grid>
        <DataGrid x:Name="testDG" ItemsSource="{Binding tempData}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Name}">
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="{x:Type TextBlock}">
                            <Setter Property="Background" Value="{Binding Name, Converter={StaticResource NameToBrushConverter}}"/>
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    

    转换器类:

    public class NameToBrushConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        string input = value as string;
        switch (input)
        {
            case "Smith":
                return Brushes.LightGreen;
            case "Willam":
                return Brushes.LightPink;
            default:
                return DependencyProperty.UnsetValue;
        }
     }
     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
     {
        throw new NotSupportedException();
     } }
    

    【讨论】:

    • 感谢您的回答。正如您在我的代码中看到的,列名是在 c# 代码中动态填充的。所以我不能像{Binding Name}那样给出。我需要访问每个单元格的值,如果它的 0 - red 、 1 - Yellow 、 2 - red 是这样的。正如我之前所说,列的数量和列的名称不能在 xaml 中硬编码,是动态填充的。
    • 它们是如何动态填充的,您根据什么更改颜色。你能在Tag 中放一些东西,然后将DataTrigger 绑定到那个吗?
    • @user8478480 我在 C# 代码中创建列,如下所示: foreach (string num in numbersList) { table.Columns.Add(num, typeof(string)); //将每个数字添加为表中的列细胞。示例单元格为 0 需要为灰色,值为 1 需要为黄色,2 为绿色。
    • 您最好将DataGrid 绑定到集合并在XAML 中手动定义列模板,这样您就可以获得所需的触发器。
    • 您对如何在 xaml 中动态填充列并从 c# 绑定数据有任何指示
    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 2015-08-22
    • 2020-06-02
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    相关资源
    最近更新 更多