HOWTO: Using WPF Converters to style the XamDataGrid

John Doe / Tuesday, January 12, 2010

There have been a lot of forums posts and questions about how to use Converters and how to bind them to the a cell, multiple cells, or something else.

I have tried to summarize all of these requirements in one place and would be happy to update the sample project on your feedback.

How WPF Value Converters work : they are classes (that implement IValueConverter or IMultiValueConverter interfaces) that provide the ability (custom logic) to convert value(s) of one type to another and vice versa. They can also be used to convert values of the same type, but that is not really what they are meant to do. One really common case is to convert an integer value (for example the Age of a Person) to a Brush or a Color.

The screenshot below covers couple of scenarios:

1. Record Background formatting based on a cell's value ( blue for male, red for female)

2. Cell Background formatting based on the cell's value (Probation field)

3. Advanced Cell formatting based on the cell's value (Age field)

4. Formatting based on multiple cells' values (Salary field)

For example :

 

public class AgeToBrushConverter : IValueConverter

    {

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

        {

            if (value == null)

                return Binding.DoNothing;

           if (value is int)

            {

                int temp = (int)value;

                if (temp < 0)

                    return Brushes.Red;

                if (temp > 0 && temp <= 10)

                    return Brushes.Black;

                if (temp > 10 && temp <= 15)

                    return Brushes.Blue;

                if (temp > 15)

                    return Brushes.DarkGreen;

            }

            return Binding.DoNothing;

        }

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

        { throw new NotImplementedException(); }

    }

 

 

You can find the full sample and source code with comments in the attachments of this blog post.

DynamicStyling.zip