WPF使用转换器更改DataGrid单元背景颜色



我有一个wpf datagrid。我需要比较两列的DateTime类型,根据比较结果,我为当前列和行中的两个单元格设置了单元背景颜色。我为每个datagrid行这样做。为此,我使用一个转换器。

<my:DataGridTextColumn Binding="{Binding Path=Date1, StringFormat={0:dd/MM/yyyy}}" Header="Date">
    <my:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="Background">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource CellDateColorConverter}">
                        <Binding Path="Date1"/>
                        <Binding Path="Date2"/>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
         </Style>
    </my:DataGridTextColumn.ElementStyle>
</my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Path=Date2, StringFormat={0:dd/MM/yyyy}}" Header="Date">
    <my:DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="Background">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource CellDateColorConverter}">
                        <Binding Path="Date1"/>
                        <Binding Path="Date2"/>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
         </Style>
    </my:DataGridTextColumn.ElementStyle>
</my:DataGridTextColumn>

转换器:

public class CellDateColorConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values[0] is DateTime && values[1] is DateTime)
        {
            DateTime date1 = (DateTime)values[0];
            DateTime date2= (DateTime)values[1];                
            if (date1.Date > date2.Date)
            {
                return Color.Brown;
            }
        }
        return ????? // I need to return the default datagrid cell's background color. How to do this?
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("CellDateColorConverter is a OneWay converter.");
    }
}

在这里我有两个问题:

  1. date1> date2 celm背景颜色未更新为棕色。
  2. 如果date1&lt; = date2,则应返回默认的datagrid单元格背景颜色,我不知道该怎么做。

我也为DataGrid定义了行样式。行样式根据某些条件设置整个行背景颜色。但是在这种情况下,这些条件不满足,但是上面的列样式(date1.date> date2.date)确实可以用棕色绘画。

利用这篇文章,如果满足行样式的条件,则将整个背景设置为橙色,如果还可以满足细胞列样式(上面的帖子),并且需要用棕色绘画,则哪个占上风?行样式或单元格式?

  1. 返回Brush

    if (date1.Date > date2.Date)
    {
        return System.Windows.Media.Brushes.Brown;
    }
    
  2. 返回System.Windows.Data.Binding.DoNothing

以下工作也有效:

return DependencyProperty.UnsetValue

最新更新