简体   繁体   中英

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. 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. 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.

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. 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. After that it is just attaching the converter on the data binding for the foreground or background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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