views:

5

answers:

1

I was looking to colour the rows of my datagrid as per a datetime column to which is populated by an ObjectDataProvider, my question is whether this is possible within XAML? Mashed up some sample code of what I'd like, a datetime comparison based on one of the , then colour that row as applicable.

 <Style.Triggers>
    <Trigger Property="DateTimeColumn" Value="dateisbeforetoday" >
      <Setter Property="Background" Value="Yellow" />
    </Trigger>
    <Trigger Property="DateTimeColumn" Value="dateaftertoday" >
      <Setter Property="Background" Value="Red" />
    </Trigger>
  </Style.Triggers>

I was thinking of iterating my way through each row and colouring it, but I thought this would be messy, and the sorting might screw things up.

A: 

A standard pattern is to create an IValueConverter that converts your object to True or False based on the comparison.

In code:

public class IsBeforeTodayConverter
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
        {
            return ((DateTime)value).Date < DateTime.Now.Date;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

In XAML:

<Style.Resources>
    <local:IsBeforeTodayConverter x:Key="IsBeforeTodayConverter" />
</Style.Resources>
<Style.Triggers>
    <DataTrigger
        Binding="{Binding DateTimeColumn,
            Converter={StaticResource IsBeforeTodayConverter}}"
        Value="True">
        <Setter Property="Background" Value="Yellow"/>
    </DataTrigger>
</Style.Triggers>

You could create a similar converter for IsAfterToday, or generalize that class by taking a ConverterParameter.

Quartermeister