字符串格式正负值和条件颜色格式化 XAML

iCo*_*min 2 wpf xaml

我正在寻找一种使用以下标准格式化我的结果的简单方法:如果是肯定的,添加一个加号并将其显示为绿色,如果它是负数,则添加一个减号并显示为红色。

我已经完成了一半,我只是不知道获得颜色格式的最简单方法是什么。有没有不使用值转换器的方法?

<TextBlock Text="{Binding Path=ActualValue, StringFormat='({0:+0.0;-0.0})'}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)

解决这个问题最聪明的方法是什么?谢谢你。

Sza*_*zsi 5

我认为没有转换器就无法做到这一点。这是可以为数字类型(除了char)完成这项工作的一个:

[ValueConversion(typeof(int), typeof(Brush))]
[ValueConversion(typeof(double), typeof(Brush))]
[ValueConversion(typeof(byte), typeof(Brush))]
[ValueConversion(typeof(long), typeof(Brush))]
[ValueConversion(typeof(float), typeof(Brush))]
[ValueConversion(typeof(uint), typeof(Brush))]
[ValueConversion(typeof(short), typeof(Brush))]
[ValueConversion(typeof(sbyte), typeof(Brush))]
[ValueConversion(typeof(ushort), typeof(Brush))]
[ValueConversion(typeof(ulong), typeof(Brush))]
[ValueConversion(typeof(decimal), typeof(Brush))]
public class SignToBrushConverter : IValueConverter
{
    private static readonly Brush DefaultNegativeBrush = new SolidColorBrush(Colors.Red);
    private static readonly Brush DefaultPositiveBrush = new SolidColorBrush(Colors.Green);
    private static readonly Brush DefaultZeroBrush = new SolidColorBrush(Colors.Green);

    static SignToBrushConverter()
    {
        DefaultNegativeBrush.Freeze();
        DefaultPositiveBrush.Freeze();
        DefaultZeroBrush.Freeze();
    }

    public Brush NegativeBrush { get; set; }
    public Brush PositiveBrush { get; set; }
    public Brush ZeroBrush { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!IsSupportedType(value)) return DependencyProperty.UnsetValue;

        double doubleValue = System.Convert.ToDouble(value);

        if (doubleValue < 0d) return NegativeBrush ?? DefaultNegativeBrush;
        if (doubleValue > 0d) return PositiveBrush ?? DefaultPositiveBrush;

        return ZeroBrush ?? DefaultZeroBrush;
    }

    private static bool IsSupportedType(object value)
    {
        return value is int || value is double || value is byte || value is long ||
               value is float || value is uint || value is short || value is sbyte || 
               value is ushort || value is ulong || value is decimal;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

<local:SignToBrushConverter x:Key="SignToBrushConverter" />

<TextBlock Text="{Binding Path=ActualValue, StringFormat='({0:+0.0;-0.0})'}" 
           Foreground="{Binding ActualValue, Converter={StaticResource SignToBrushConverter}}" />
Run Code Online (Sandbox Code Playgroud)

或者,如果您想覆盖默认颜色:

<local:SignToBrushConverter x:Key="SignToBrushConverter" NegativeBrush="Purple" PositiveBrush="DodgerBlue" ZeroBrush="Chocolate" />
Run Code Online (Sandbox Code Playgroud)