【问题标题】:How do I change the background color of a cell by a condition?如何通过条件更改单元格的背景颜色?
【发布时间】:2019-10-12 13:40:02
【问题描述】:

如何通过数值条件更改单元格的背景颜色?

例如,当价格大于10时,背景为红色。

我这样做了,但值保持不变,例如,我希望这适用于所有大于 100 的值。 抱歉我的英语不好

  <DataGridTextColumn Binding="{Binding Price}"
        Header="Price">
        <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <Trigger Property="Text" Value="100">
                        <Setter Property="Foreground" Value="Red"/>
                        <Setter Property="FontWeight" Value="Bold"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGridTextColumn.ElementStyle>
    </DataGridTextColumn>

【问题讨论】:

  • 您能否为这个示例展示一个示例 xaml?
  • 请分享一些代码,或详细说明您的问题,以便我们了解您的要求和帮助。
  • Corentin Pane,布兰登,好的
  • @CorentinPane 好的
  • @Branden 我更新了我的问题

标签: c# wpf xaml


【解决方案1】:

您可以使用IValueConverter 将价格转换为颜色并定义DataGridTextColumn.CellStyle 以使用此转换器。

在代码中的某处定义:

public class PriceToBackgroundColorConverter : IValueConverter {
    // Converts a value into a color.
    // Returns Red if value is greater than 100, else White.
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        int price = (int)value;
        if (price > 100) {
            return Brushes.Red;
        } else {
            return Brushes.White;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }
}

现在您可以通过将其添加到您的DataGrid(或任何父控件)的Resources 并使用Setter 为所有DataGridCell 对象设置样式来使用此转换器。

    <DataGrid ItemsSource="{Binding Items}">
        <DataGrid.Resources>
            <wpfapp1:PriceToBackgroundColorConverter x:Key="PriceToBackgroundColorConverter"></wpfapp1:PriceToBackgroundColorConverter>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Price}" Header="Price">
                <DataGridTextColumn.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Background" Value="{Binding Path=Price, Converter={StaticResource PriceToBackgroundColorConverter}}"></Setter>
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

这将指示您的DataGridTextColumnStyle 应用于其所有DataGridCell 子级,并且此Style 通过@987654336 将每个DataGridCellBackground 属性绑定到其Price 属性@。

您可以更改转换器代码以执行您想要的任何类型的逻辑,为不同的范围设置多种颜色等。

您还可以定义更多转换器和更多Setter 来更改其他属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-03
    • 2014-05-03
    • 1970-01-01
    • 2020-04-28
    • 2018-09-19
    • 2011-09-24
    • 2013-04-12
    • 2021-10-31
    相关资源
    最近更新 更多