我有一个WPF数据网格。我需要比较两个类型为datetime的列,根据比较结果,我为当前列和行中的两个单元格设置了单元格背景颜色。我为每个数据网格行执行此操作。为此,我使用转换器。
<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.");
}
}
这里有两个问题:
此外,我还为datagrid定义了一种行样式。行样式根据某些条件设置整个行背景颜色。但在这种情况下,这些条件不满足,但上面的列样式(date1.Date&gt; date2.Date)确实如此,因此单元格背景应该用棕色绘制。
利用这篇文章,如果满足行样式的条件,并且整个背景设置为例如橙色,如果单元格样式(在此帖子中上面)也满足并且需要涂成棕色,那么哪个占上风?行样式或单元格样式?
答案 0 :(得分:2)
返回Brush
:
if (date1.Date > date2.Date)
{
return System.Windows.Media.Brushes.Brown;
}
返回System.Windows.Data.Binding.DoNothing
。