#1,139 – Value Converter Example for Input
August 19, 2014 2 Comments
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: