I want the foreground color of a DataGridColumn
to 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 the 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 shows no effect.
its because all regular DataGridColumn
Binding's are relative of the DataGrid
element, not the Row. in The DataGrid level no property named Change
, only in row level.
Solution is: using 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 Binding in a WPF data grid text column for more solutions.
foreground color of a DataGridColumn to change based on its value if value is negative then color is red other black xmal code is`
<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>`
code in viewmodel is
if(model.salesContribution<0)
{
model.ColorSet="Red";
}
else
{
model.ColorSet="Black";
}
add colorset variable is model
public string ColorSet { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With