WPF Datagrid中的单个单元格背景颜色并非全部为行颜色

时间:2019-02-12 16:00:48

标签: c# wpf cell background-color wpfdatagrid

我已经编写了这段代码来更改WPF mydatagrid中单元格的颜色,但是结果是所有行都被着色了,我不知道为什么。

Style style = this.FindResource("backColor") as Style;
DataGridClientFile.CellStyle = style;


<Style x:Key="backColor" TargetType="DataGridCell">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Colore}" Value="Red">
                        <Setter Property="Background" Value="Red"/>
                        <Setter Property="Foreground" Value="White"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=Colore}" Value="Green">
                        <Setter Property="Background" Value="Green"/>
                        <Setter Property="Foreground" Value="White"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=Colore}" Value="Yellow">
                        <Setter Property="Background" Value="Yellow"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=Colore}" Value="Cyan">
                        <Setter Property="Background" Value="Cyan"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Path=Colore}" Value="White">
                        <Setter Property="Background" Value="White"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>

1 个答案:

答案 0 :(得分:0)

解决方法:

Style style = this.FindResource("backColor") as Style;
Style styleNX = this.FindResource("backColorNX") as Style;
if (DataGridClientFile.Columns.Count >= 14)
            {
                DataGridColumn col = DataGridClientFile.Columns[14];
                col.CellStyle = style;
                DataGridColumn colNX = DataGridClientFile.Columns[15];
                colNX.CellStyle = styleNX;
            }