Style DataGridCell background based on column binding

Nov 6, 2008 at 3:50 PM
I'm using a DataGrid with DataGridTextColumns that are bound to DateTime properties, with StringFormat {0:dd}, something like a calendar.  I have a converter that I would like to use to set the background of each cell based on the full DateTime value, not just the formatted day string.  How would this be done?  Rather, how can I access the original DateTime value from a given DataGridCell?
Coordinator
Nov 6, 2008 at 5:18 PM

Something like this should work for you....

                <dg:DataGridTextColumn Binding="{Binding Path=BirthDate, StringFormat=0:dd}">

                    <dg:DataGridTextColumn.CellStyle>

                        <Style TargetType="dg:DataGridCell">

                            <Setter Property="Background" Value="{Binding Path=BirthDate, Converter={StaticResource myconverter}}"></Setter>

                        </Style>

                    </dg:DataGridTextColumn.CellStyle>

                </dg:DataGridTextColumn>

    // A crude implementation of DateTime to Brush converter

    public class MyConverter : IValueConverter

    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        {

            DateTime dateTime = (DateTime)value;

            if (dateTime < DateTime.Today.AddDays(-1100))

            {

                return new SolidColorBrush(Colors.Red);

            }

            else

            {

                return new SolidColorBrush(Colors.Green);

            }

        }

 

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

        {

            throw new NotSupportedException();

        }

    }