Search code examples
wpfxamllistboxtextblock

Text color depends of value


First of all, I am new to WPF and Xaml, so I just hope that you understand what I am asking.

I got this situation: There is a listBox of Animals. Every Animal has Weight property. What I am trying to achieve is whenever Weight of Animal is greater then 300 kg, that Weight should be displayed red.


Solution

  • You could use custom converter to achieve that. If your item looks like that:

    public class Animal
    {
        public int Weight { get; set; }
        public string Name { get; set; }
    }
    

    and ItemTemplate like that:

    <DataTemplate x:Key="AnimalTemplate">
        <TextBlock Text="{Binding Name}" Foreground="{Binding Weight, Converter={StaticResource AnimalColorSelector}}"/>
    </DataTemplate>
    

    Your converter will be like the following one:

    public class AnimalColorSelector : IValueConverter
    {
        private readonly Color _overweightColor = Colors.Red;
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int)
            {
                return (int) value > 300 ? new SolidColorBrush(_overweightColor) : Binding.DoNothing;
            }
    
            return Binding.DoNothing;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    This approach has the following pros:

    1. You don't need to hardcode the default color, but inherit it by using Binding.DoNothing.
    2. You don't need to store any style information in a view model.