#1,139 – Value Converter Example for Input

The ConvertBack method of a value converter is used to convert from a binding target (e.g. the attribute of a control) to a binding source (e.g. a property).  Below is a simple example, showing how we can convert from a Slider value to the square root of the selected value.

In XAML, we have a Slider that ranges from 1-100 and binds to a property that is meant to store the square root of the selected value.  We specify a binding Mode to indicate that binding should only map from the target (the Value property) to the source (the SqRootValue property) and not in the other direction.  We then include labels that bind to the Slider’s Value property as well as the SqRootValue property.

<Window x:Class="WpfApplication1.MainWindow"
        Title="Value Converter" SizeToContent="WidthAndHeight">

        <local:IntToRootConverter x:Key="intToRootConverter"/>

    <StackPanel Margin="15">
        <Slider x:Name="slider" Minimum="1" Maximum="100"
                Value="{Binding Path=SqRootValue,
                                Converter={StaticResource intToRootConverter},
        <Label Content="{Binding ElementName=slider, Path=Value}"/>
        <Label Content="{Binding SqRootValue}"/>

The code-behind is straightforward.

    public partial class MainWindow : Window, INotifyPropertyChanged
        public MainWindow()
            this.DataContext = this;

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged(string prop)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));

        private double sqRootValue;
        public double SqRootValue
            get { return sqRootValue; }
                if (sqRootValue != value)
                    sqRootValue = value;

In the value converter, we just take the square root of the current value, calculating the result in ConvertBack.

    public class IntToRootConverter : IValueConverter
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            throw new NotImplementedException();

        // Convert from int (target of binding) to double representing square root (source of binding)
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            double root = Math.Sqrt((double)value);
            return root;

At run-time: