WPF Value Conversion

When data binding, the type of the control property is not always the same as the model source property. Te type or the display format of a property can be changed by implementing a value converter.

The value converter is a class that implements IValueConverter :

namespace CharacterForms.ValueConverter
{
    [ValueConversion(/*model type*/ typeof(int), 
                     /*control type*/ typeof(Brush))]
    class DebtIndicator : IValueConverter
    {

        public object Convert(object value, 
                              Type targetType, 
                              object parameter, 
                              CultureInfo culture)
        {
            if (targetType != typeof(Brush))
            {
                return null;
            }

            string valString = (value == null) 
                               ? null
                               : value.ToString() ;

            int val = (string.IsNullOrWhiteSpace(valString) )
                      ? 0 
                      :int.Parse(value.ToString());

            return (val < 0) 
                   ? Brushes.Red 
                   : Brushes.White;
        }

        public object ConvertBack(object value, 
                                 Type targetType, 
                                 object parameter, 
                                 CultureInfo culture)
        {
            //shouldn't need to convert back.
            throw new NotImplementedException();
        }
    }

In this case the value converter chooses a red or white brush based on whether the value is negative (red), 0 (white) or positive (white).

This can be bound to the background of a text box to highlight negative values as follows, first an instance of the converter must be declared as a resource:

    <Window.Resources>
        <vc:DebtIndicator x:Key="di"/>
    </Window.Resources>

And then the Background property bound to the field that will be used to determine it’s background colour:

<TextBox ... Background="{Binding Path=Key, Converter={StaticResource di}}"/>

A simple example of a converter that would use both methods, consider a text field that displayed an integer in hex format, that could be edited by the user.
 

Leave a Reply