【问题标题】:single cell background color in WPF Datagrid not all row colorWPF Datagrid中的单个单元格背景颜色不是所有的行颜色
【发布时间】:2019-07-06 08:04:17
【问题描述】:

我已经编写了这段代码来更改 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>

【问题讨论】:

  • 您设置了DataGrid 本身的CellStyle 属性,不是吗?您希望将您的样式应用到哪个单元格? DataGridColumn 有一个 CellStyle 属性,可用于更改该特定列中单元格的样式,如果这是您想要的。
  • 太棒了!正是我需要的。谢谢。
  • 为什么不使用转换器将字符串转换为颜色
  • 是的!好问题。主要问题是我在理解 DataContext 时遇到了一些问题。我为数据网格中的行创建了一个类,然后使用 iNotifyPropertyChanged 创建了一个模型视图类并将其绑定到 DataGrid。好的,它可以工作,因为我在后面的代码中通过 C# 设置了数据上下文。我无法在 XAML 上设置数据上下文,也无法理解如何只转换我需要的列。

标签: c# wpf cell background-color wpfdatagrid


【解决方案1】:

解决办法:

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;
            }

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 2011-04-03
    • 2013-01-28
    • 2015-05-14
    • 1970-01-01
    • 2020-06-02
    • 2023-03-28
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多