【发布时间】:2019-11-22 08:35:49
【问题描述】:
我想在 DataGridTextColumn 中以红色显示负货币,并在括号中显示负货币,例如 ($200.00)。 只要金额为负,我就可以使用转换器将前景转换为红色,如下面的 XAML 所示。 但是,当我尝试包含诸如 Binding="{Binding Path=NonTaxable, StringFormat=c2}" 之类的字符串格式时,前景色转换失败。
如何显示负货币
(a) 红色
(b) 在括号中
(c) 带有 $ 货币符号?
这里是 XAML 和代码。
<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();
}
}
【问题讨论】: