简体   繁体   English

C#WPF中DataGrid的颜色单元格

[英]color cells of a DataGrid in C# WPF

I am developing a program that reviews the bus voltages of a given grid, and those voltages are displayed in a DataGrid. 我正在开发一个程序,该程序检查给定网格的总线电压,这些电压显示在DataGrid中。 The user can set the boundaries to consider a bus voltage as "normal" outside those limits the voltage is marked as erroneous. 用户可以设置边界,以将总线电压视为标记为错误的那些限制之外的“正常”电压。

Example:
Upper limit: 1.05
Lower limit: 0.95

  1     2     3
A 0.93  0.96  1.02
B 1.03  0.91  1.08
C 0.95  1.00  0.98

Therefore the erroneous will be: A1, B2 and B3

I would like to color the error cells in red. 我想将错误单元涂成红色。

I have seen many answers that solve the thing through XAML. 我已经看到许多通过XAML解决问题的答案。 I'm new to WPF, but all the XAML solutions seems to be static, and defined at design time, and what I need is to change the color at run time because the user can change the criteria. 我是WPF的新手,但是所有XAML解决方案似乎都是静态的,并且是在设计时定义的,我需要的是在运行时更改颜色,因为用户可以更改标准。

Basically what I want is change the color based on dynamic parameters. 基本上我想要的是根据动态参数更改颜色。 And not in all columns because the table contains other parameters that are not voltages, such as angles and currents. 并且并非在所有列中,因为该表包含的不是电压的其他参数,例如角度和电流。

Any help is appreciated. 任何帮助表示赞赏。 Thank you in advance. 先感谢您。

You need a ValueConverter or a MultiValueConverter. 您需要一个ValueConverter或MultiValueConverter。 Below is a simple example that "should" work but as I wrote it from memory it may be slightly wrong though should give you an idea. 下面是一个“应该”工作的简单示例,但是正如我从内存中写的那样,虽然应该会给您一个思路,但可能会略有错误。

[ValueConversion(typeof(decimal), typeof(Brush))]
public class BusVoltagesColorConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || !(value is decimal))
        {
            return DependencyProperty.UnsetValue;
        }
        var d = (decimal) value;
        decimal lowerLimit = 0.95m; //TODO get your value from your user settings here
        decimal upperLimit = 1.05m;
        if (d < lowerLimit || d > upperLimit)
        {
            return Brushes.Red;
        }
        return Brushes.Black;
    }

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

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new BusVoltagesColorConverter();
    }
}

Then on your WPF page you need to add it as a resource. 然后,需要在WPF页面上将其添加为资源。 After that it is just attaching the converter on the data binding for the foreground or background. 之后,它只是将转换器附加到前景或背景的数据绑定上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM