I have a WPF datagrid and have a datatemplate column called "Requested Date Out Source." The application should look at the date in the cell and change the color based on if it's today, past, or future.
I have the Ivalueconverter:
public class FBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input = value as string;
{
if (input == "Select a date")
{
return new SolidColorBrush(Colors.Black);
}
else
{
DateTime dt = System.Convert.ToDateTime(input);
switch (true)
{
case true when (dt == DateTime.Today):
return new SolidColorBrush(Colors.Yellow);
case true when (dt < DateTime.Today):
return new SolidColorBrush(Colors.Red);
case true when (dt > DateTime.Today):
return new SolidColorBrush(Colors.Blue);
default:
//return Brushes.Black;
return new SolidColorBrush(Colors.Black);
}
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
I have the XAML:
<DataGridTemplateColumn x:Name="DateoutSource" Header="Requested 
 Date Out Source" Width="125" SortMemberPath="DateOutSource" SortDirection="Ascending" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker x:Name="BtnDateOutSource" SelectedDate="{Binding DateOutSource}" SelectedDateChanged="BtnDateOutSource_SelectedDateChanged" Foreground="{Binding Converter={StaticResource FBrushConverter}}">
</DatePicker>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
The result is that the column is always red:
Tracing through the code indicates that the Convert Object value is always NULL which is why the display is always red.
This implies some issues with the binding. I have tried a variety of approaches with no luck.
Any ideas on this one? Thanks in Advance, Kerry
Bind the Foreground
property to DateOutSource
property as suggested by @Xiaoy312:
Foreground="{Binding DateOutSource, Converter={StaticResource FBrushConverter}}"
Then you also need to modify your converter to cast the value to a DateTime?
which I assume is the actual type of DateOutSource
:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DateTime? dt = (DateTime?)value;
if (!dt.HasValue)
return new SolidColorBrush(Colors.Black);
DateTime date = dt.Value.Date;
if (date == DateTime.Today)
return new SolidColorBrush(Colors.Yellow);
else if (date < DateTime.Today)
return new SolidColorBrush(Colors.Red);
else if (date > DateTime.Today)
return new SolidColorBrush(Colors.Blue);
return new SolidColorBrush(Colors.Black);
}