WPF Convert IMultiValueConverter Result to Target Type
By Michael Detras
If the result of a Convert method of an IMultiValueConverter does not get shown on the data-bound control, then it is possible you forgot to convert the result to the target type.
There were a couple of times where I created an IMultiValueConverter class and the result of the Convert method does not get shown in the UI. I always forget to cast the return value to the target type since this is done automatically when using an IValueConverter. Let's say we have the following IMultiValueConverter:
class AdditionConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double addend1 = (double)values[0];
double addend2 = (double)values[1];
double sum = addend1 + addend2;
return sum;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And here is a TextBox where the Text property binding uses the converter.
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource ResourceKey=AdditionConverter}">
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="SomeDouble1" Mode="OneWay"/>
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="SomeDouble2" Mode="OneWay"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
We might think that the result of the Convert method is automatically converted to a string. Instead, nothing is shown in the TextBox and we get the following the error in the Output window: System.Windows.Data Error: 5
: Value produced by BindingExpression is not valid for target property.; Value='17'
MultiBindingExpression:target element is 'TextBox' (Name=''); target property
is 'Text' (type 'String').
If we used a ToString() method on the sum variable, then it works as expected. Meanwhile, if we have an IValueConverter like the following, the output will be shown even if we did not convert the return value from double to string.
class PowerOfTwoConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double x = (double)value;
return x * x;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Related FAQs
When using converters for data binding, we usually use the Convert method of an IValueConverter and just leave the ConvertBack method unimplemented. The ConvertBack method lets us update the binding source.
This shows how to bind a dependency property to more than 1 binding source using multi-binding.
WPF Convert IMultiValueConverter Result to Target Type (2476 Views)