Stock
) to red.
Minimum 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 list of information of class Data
and passing it to Background
in the Stock column will have the following marking:
<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 this mark there is Data
with DataGrid
who is responsible for checking this condition.
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 like this:
DataGrid_Color(Grid);
How to change single cell color of datagrid in wpf? - SO In