WPF DataGridColumn foreground color turns red if value is negative
I want the foreground color to DataGridColumn
change based on its value. I have
<DataGridTextColumn x:Name="Diff1"
Binding="{Binding Change}" Header="Net Chng"
Width="*" IsReadOnly="True"
Foreground="{Binding Change,Converter={StaticResource negativeToColor}}">
</DataGridTextColumn>
and converter
public class negativeToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SolidColorBrush brush = new SolidColorBrush(Colors.LimeGreen);
double doubleValue = 0.0;
Double.TryParse(value.ToString(), out doubleValue);
if (doubleValue < 0)
brush = new SolidColorBrush(Colors.Red);
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
But the converter has no effect.
source to share
because all the regular bindings DataGridColumn
are on the element DataGrid
, not the string. there is no named property at the DataGrid level Change
, only at the row level.
Solution: use DataGridTemplateColumn
.
<DataGridTemplateColumn Header="Net Chng" Width="*" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Change}" Foreground="{Binding Change, Converter={StaticResource negativeToColorConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
EDIT: See Linking in WPF Text Data Table Column for more solutions.
source to share
the foreground color of the DataGridColumn to change based on its value, if the value is negative then the color is red, the other code is black xmal '
<Local:AlphabetTextColumn
Header=" Contribution %"
x:Name="SalesaAmount2"
Binding="{Binding salesContribution}"
>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="{Binding ColorSet}" />
</Style>
</DataGridTextColumn.ElementStyle>
</Local:AlphabetTextColumn>'
the code in the viewmodel is
if(model.salesContribution<0)
{
model.ColorSet="Red";
}
else
{
model.ColorSet="Black";
}
add variable colorset this is the model
public string ColorSet { get; set; }
source to share