Search code examples
wpftriggersstylestextblockdatatrigger

WPF TextBlock Negative Number In Red


I am trying to figure out the best way to create a style/trigger to set foreground to Red, when value is < 0. what is the best way to do this? I'm assuming DataTrigger, but how can I check for negative value, do i have to create my own IValueConverter?


Solution

  • If you are not using an MVVM model (where you may have a ForegroundColor property), then the easiest thing to do is to create a new IValueConverter, binding your background to your value.

    In MyWindow.xaml:

    <Window ...
        xmlns:local="clr-namespace:MyLocalNamespace">
        <Window.Resources>
            <local:ValueToForegroundColorConverter x:Key="valueToForeground" />
        <Window.Resources>
    
        <TextBlock Text="{Binding MyValue}"
                   Foreground="{Binding MyValue, Converter={StaticResource valueToForeground}}" />
    </Window>
    

    ValueToForegroundColorConverter.cs

    using System;
    using System.Windows.Media;
    using System.Windows.Data;
    
    namespace MyLocalNamespace
    {
        class ValueToForegroundColorConverter: IValueConverter
        {
            #region IValueConverter Members
    
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                SolidColorBrush brush = new SolidColorBrush(Colors.Black);
    
                Double doubleValue = 0.0;
                Double.TryParse(value.ToString(), out doubleValue);
    
                if (doubleValue < 0)
                    brush = new SolidColorBrush(Colors.Red);
    
                return brush;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    
            #endregion
        }
    }