I want to show negative currencies in a DataGridTextColumn in red and also in brackets such as ($200.00). I am able to convert the foreground to Red whenever the amount is negative using a converter as shown in the following XAML. However, when I try to include a string format such as Binding="{Binding Path=NonTaxable, StringFormat=c2}" the foreground color conversion fails.
How can I show negative currencies
(a) in Red
(b) in Brackets
(c) with a $ currency sign?
Here are the XAML and codes.
<DataGridTextColumn Width="*" Header="NonTaxable" Binding="{Binding Path=NonTaxable}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource NegativeValueConverter}}" Value="-1" >
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
VB.Net
Imports System.Globalization
Public Class NegativeValueConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
Dim doubleValue As [Double] = 0.0
If value IsNot Nothing Then
If [Double].TryParse(value.ToString(), doubleValue) Then
If doubleValue < 0 Then
Return -1
End If
End If
End If
Return 1
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Throw New NotImplementedException()
End Function
End Class
C#
using System.Globalization;
public class NegativeValueConverter : IValueConverter
{
public object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Double doubleValue = 0.0;
if (value != null) {
if (Double.TryParse(value.ToString(), doubleValue)) {
if (doubleValue < 0) {
return -1;
}
}
}
return 1;
}
public object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}