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

时间:2017-10-07 00:14:03

标签: wpf xaml

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

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

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

最明智的方法是什么?谢谢。

2 个答案:

答案 0 :(得分:2)

我不认为你可以在没有转换器的情况下做到这一点。这是一个可以完成数字类型工作的人(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();
    }
}

用法:

<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" />

答案 1 :(得分:2)

正确的方法是使用数据触发器,因为通常情况下,前景和字符串格式可能不仅仅是要更改的属性。在大多数情况下,数据触发器用于更改控件的 DataTemplate

以下是您案例的代码示例:

<Window.Resources>

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

    <Style TargetType="TextBlock" x:Key="NumericTextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource PositiveConverter}}" Value="True">
                <Setter Property="Foreground" Value="Green"/>
                <Setter Property="Text" Value="{Binding StringFormat='({0:+0.0})'}"/>
            </DataTrigger>

            <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource PositiveConverter}}" Value="False">
                <Setter Property="Foreground" Value="Red"/>
                <Setter Property="Text" Value="{Binding StringFormat='({0:-0.0})'}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>

<Grid>

    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">

        <TextBlock Text="{Binding Positive}" Style="{StaticResource NumericTextBlock}"/>

        <TextBlock Text="{Binding Negative}" Style="{StaticResource NumericTextBlock}"/>

    </StackPanel>

</Grid>

代码背后:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Positive = 4;
        Negative = -7;
        InitializeComponent();
        DataContext = this;
    }

    public double Positive { get; set; }
    public double Negative { get; set; }
}

最后转换器类:

public class PositiveConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var number = 0.0;
        var isNumber = double.TryParse(value.ToString(), out number);

        return isNumber && number >= 0.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}