Search code examples
c#wpfwpfdatagrid

How to make conditional DataTrigger in WPF


I wanna make coloring DataGridRow in my datagrid using style in WPF. I wanna make percentage of coloring based on value. If I have value binding Error between 0 and 50 it will be red. And if vice versa it will be colored as Green

But How I can do with style?

 <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Error}" Value="Error>50"> //maybe something like this
                        <Setter Property="Foreground" Value="#FFE08F8F" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Error}" Value="2">
                        <Setter Property="Foreground" Value="#FF6DBB6D" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

Solution

  • IMO the most flexible solution will be to add some kind of ErrorToColor converter. Then use this XAML:

    <Setter Property="Foreground" >
        <Setter.Value>
            <SolidColorBrush Color="{Binding Error, Converter={StaticResource errorToColorConverter}}" />
        </Setter.Value>
    </Setter>
    

    Such converter could look like this:

    public class IntToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {            
            return value is int && ((int)value) > 50 ? Colors.Green : Colors.Red;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    This way you can easily manage colors for different error values.