Alter color of the Datagrid cell

Asked

Viewed 666 times

1

I have a Datagrid in C# WPF, and I need to change the color of some cells according to one condition. For example I have the Stock column and if the Stock is less than a specific value I put its color in red. how can I do this, recover the color of mobile and assign a new color.

1 answer

2


Good as it has no context I will propose a minimum example, functioning as follows, if the field Stock class Data for 0 your cell will change the background color (Background) to red.

Minimal example

Class:

public class Data
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Stock { get; set; }
}

WPF

<Window x:Class="WpfApp1.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350"
        Width="399.702" Initialized="Window_Initialized">
    <Grid>
        <DataGrid x:Name="Grid" HorizontalAlignment="Left" ItemsSource="{Binding}"
               AutoGenerateColumns="False" Height="291"
               Margin="10,10,0,0" VerticalAlignment="Top"
               Width="369" CanUserReorderColumns="False"
               CanUserResizeColumns="False" CanUserSortColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=Id}"
                    Header="Id" Width="50" IsReadOnly="True"/>
                <DataGridTextColumn Binding="{Binding Path=Name}"
                    Header="Name" Width="250" IsReadOnly="True"/>
                <DataGridTextColumn Binding="{Binding Path=Stock}"
                    Header="Stock" Width="50" IsReadOnly="True">
                    <DataGridTextColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Stock}" Value="0">
                                    <Setter Property="Background">
                                        <Setter.Value>
                                            <SolidColorBrush Color="Red"/>
                                        </Setter.Value>
                                    </Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTextColumn.CellStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>            
        </DataGrid>
    </Grid>    
</Window>

When filling in the class information list Data and pass it on to DataGrid in the Stock column you will have the following markup:

<DataGridTextColumn Binding="{Binding Path=Stock}"
        Header="Stock" Width="50" IsReadOnly="True">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Stock}" Value="0">
                        <Setter Property="Background">
                            <Setter.Value>
                                <SolidColorBrush Color="Red"/>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
</DataGrid.Columns>

in that marking there is DataGridTextColumn.CellStyle with Style.Triggerswho is responsible for verifying this condition.


In coding would also, following the same minimal example:

private void DataGrid_Color(DataGrid grid)
{
    foreach(Data item in grid.ItemsSource)
    {
        if (item != null)
        {
            if (item.Stock == 0)
            {
                DataGridRow row = (DataGridRow)grid.ItemContainerGenerator
                                                   .ContainerFromItem(item);

                DataGridCell column = grid.Columns[2].GetCellContent(row)
                                                     .Parent as DataGridCell;
                if (row != null)
                {
                    column.Background = Brushes.Red;
                }
            }
        }
    }
}

and call this method so:

DataGrid_Color(Grid);

Reference:

  • I was able to understand her example and it worked perfectly, but assuming, is it possible to access Cell from the code and add a new backgroud to it? for example, a function in my source code that will read all the Cell of my grid, and according to the data found on this phone it decides whether or not to change its color! it is possible to do this?

  • Whether it is easier to understand https://answall.com/questions/208319/alterando-cor-de-cell-de-acordo-com-condi%C3%A7%C3%A3o-no-if-em-c%C3%B3digo-source-c-wpf

  • @Brunosilva has, yes, just make one foreach in the DataGrid, I will also add this in the answer, and please if it is useful accepted as answer of your question ( just remembering that this had not as given in your question and so the initial proposal was the first solution )

  • 1

    Got it, thanks for helping me solve the problem! your answer helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.