Reputation: 10644
I have an WPF datagrid. There are two columns of type datetime which I need to compare and according to the compare result, I set a cell background color for the two cells in the current column and row. I do this for each datagrid row. In order to do this I use a converter.
<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>
The converter:
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.");
}
}
Here I have two problems:
Also I have defined a row style for the datagrid. The row style sets the entire row background color according to some conditions. But in this case, these conditions are not satisfied but the above column style (date1.Date > date2.Date) does, so cell background should be painted with brown.
Taking advantage of this post, in case conditions for row style are satisfied, and entire background is set for example to orange, if cell column style (above in this post) is also satisfied and need to be painted in brown, then which prevails? the row style or cell style?
Upvotes: 1
Views: 3445
Reputation: 1
The following works also:
return DependencyProperty.UnsetValue
Upvotes: 0
Reputation: 169270
Return a Brush
:
if (date1.Date > date2.Date)
{
return System.Windows.Media.Brushes.Brown;
}
Return System.Windows.Data.Binding.DoNothing
.
Upvotes: 4