1

I would like to write a IMultiValueConverter that converts back value (string) to an array with objects compatible with the types given in targetTypes parameter, as so:

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    if (value != null)
    {
        List<object> results = new List<object>();
        string[] arr = value.ToString().Split(' ');
        for (int i = 0; i < arr.Length; i++)
        {
            object item = (targetTypes[i])arr[i]; //ERROR: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
        }
        return results.ToArray();
    }
    else
    {
        return null;
    }
}

So, for example "London 22" I would like to convert back to "London" (string) and "2" (int). As indicated by the list of types in the targetTypes parameter. And of course, return it as an array.

However, I am not able to cast elements of this array to expected by the targetTypes parameter, as I commented in the code above.

The goal is of course to solve the problem reported during binding: "Can not save the value from target back to source.", Which occurs when an attempt is made to store the string to the int.

Which is reported when I use such a converter:

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    if (value != null)
    {
        return value.ToString().Split(' ');
    }
    else
    {
      return   null;
    }
}

1 Answer 1

1

You may try something like this:

public object[] ConvertBack(
    object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
    var strings = value.ToString().Split(' ');

    if (strings.Length != targetTypes.Length)
    {
        throw new InvalidOperationException("Invalid number of substrings");
    }

    return strings
            .Select((s, i) => System.Convert.ChangeType(s, targetTypes[i]))
            .ToArray();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.