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

2024-01-09

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

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

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

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


我认为如果没有转换器就无法做到这一点。这是可以完成数字类型工作的一个(除了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();
    }
}

Usage:

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

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

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

<local:SignToBrushConverter x:Key="SignToBrushConverter" NegativeBrush="Purple" PositiveBrush="DodgerBlue" ZeroBrush="Chocolate" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

字符串格式正值和负值以及条件颜色格式 XAML 的相关文章

随机推荐