#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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Value Converter" SizeToContent="WidthAndHeight">

    <Window.Resources>
        <local:IntToRootConverter x:Key="intToRootConverter"/>
    </Window.Resources>

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

The code-behind is straightforward.

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

        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; }
            set
            {
                if (sqRootValue != value)
                {
                    sqRootValue = value;
                    OnPropertyChanged("SqRootValue");
                }
            }
        }
    }

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:

1139-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,139 – Value Converter Example for Input

  1. Roland says:

    This Example does not work anymore with .NET4 because the Convert method is not implemented.

    • Sean says:

      I just double-checked and the example worked fine in both 4.5 and 4.6. You don’t need Convert implemented if you’re OneWayToSource binding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: