Change Datagrid Cell Colour Based on Values

How to change DataGrid cell background color based on cell value

I did the following to fix my issue:

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Height="173" Margin="53,127,0,0" VerticalAlignment="Top" Width="378" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding Selecione}" Header="Selecione"/>
<DataGridTextColumn Binding="{Binding Grupos}" Header="Grupos"/>
<DataGridTextColumn Binding="{Binding Permissoes}" Header="Permissões">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Permissoes}" Value="Modify">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>`enter code here`
</DataGrid.Columns>
</DataGrid>

Changing datagridview cell color based on condition

You need to do this

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow Myrow in dataGridView1.Rows)
{ //Here 2 cell is target value and 1 cell is Volume
if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition
{
Myrow .DefaultCellStyle.BackColor = Color.Red;
}
else
{
Myrow .DefaultCellStyle.BackColor = Color.Green;
}
}
}

Meanwhile also take a look at Cell Formatting

WPF datagrid change row color based on a property value

You current binding uses the DataContext of the individual row as binding source (which is the data model stored in the ItemsSource). But your property RowStatus is defined on the object that is the DataContext of the DataGrid (which is the LoadServerViewModel).

To make it work, you must adjust your data bindings to use the correct source (or alternatively move the RowSatus property to the data models):

<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.RowStatus}"
Value="Created">
<Setter Property="Background" Value="Yellow" />
</DataTrigger>
</Style.Triggers>
</Style>

c# change datagrid cell color

I have created a new sample with some data: you have to use a converter with multibinding to do waht you want..

mainwindows.xaml:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:WpfApplication1="clr-namespace:WpfApplication1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"

Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<WpfApplication1:HighlighterConverter x:Key="myHighlighterConverter" />
</Window.Resources>
<Grid>
<DataGrid x:Name="arcad_Grid" Loaded="arcad_Grid_Loaded" SelectionChanged="arcad_Grid_SelectionChanged"
AutoGenerateColumns="True" SelectionUnit="Cell" >
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background">
<Setter.Value>
<MultiBinding Converter="{StaticResource myHighlighterConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"></Binding>
<Binding Path="Row"></Binding>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.CellStyle>
</DataGrid>
</Grid>
</Window>

during the loaded event in mainwindow.xaml.cs:

    private void arcad_Grid_Loaded(object sender, RoutedEventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Color", typeof(string));

// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", "rouge");
table.Rows.Add(50, "Enebrel", "Sam", "vert");
table.Rows.Add(10, "Hydralazine", "Christoff", "rouge");
table.Rows.Add(21, "Combivent", "Janet", "vert");
table.Rows.Add(100, "Dilantin", "Melanie", "vert");

arcad_Grid.ItemsSource = table.DefaultView;
}

converter.cs:

using System;
using System.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Controls;

namespace WpfApplication1
{
public class HighlighterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[1] is DataRow)
{
var cell = (DataGridCell)values[0];
var row = (DataRow)values[1];
var columnName = cell.Column.SortMemberPath;

if (row[columnName].ToString() == "rouge" )
return Brushes.Red;
if (row[columnName].ToString() == "vert")
return Brushes.Green;

}
return SystemColors.AppWorkspaceColor;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
}

}

enter image description here

Another solution with a simple converter: you add this in converter.cs

public class ValueToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input;
try
{
DataGridCell dgc = (DataGridCell)value;
System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
input = (string)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
}
catch (InvalidCastException e)
{
return DependencyProperty.UnsetValue;
}
switch (input)
{
case "rouge": return Brushes.Red;
case "vert": return Brushes.Green;
default: return DependencyProperty.UnsetValue;
}
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}

modification in mainwindow.xaml:

<Window.Resources>
<WpfApplication1:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
<Style x:Key="CellStyle" TargetType="DataGridCell">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
</Style>
</Window.Resources>
<Grid>
<DataGrid x:Name="arcad_Grid" Loaded="arcad_Grid_Loaded" SelectionChanged="arcad_Grid_SelectionChanged"
AutoGenerateColumns="True" SelectionUnit="Cell" CellStyle="{StaticResource CellStyle}" >
</DataGrid>
</Grid>

same result with less coding



Related Topics



Leave a reply



Submit