Search code examples
c#wpfdata-bindingobjectivalueconverter

IValue Converter: ConvertBack - String to Object


I can get convert to work from an object to a textbox. But I am a little loss at convertback. Any lead or help is much appreciated.

 [ValueConversion(typeof(Object), typeof(String))] 
 public class DataConverter : IValueConverter
 {
    // This converts the DateTime object to the string to display.
    public object Convert(object value, Type targetType, object parameter, CultureInfo   culture)
    {
      BasePar data = (BasePar)value;
      return data.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      string strValue = value as string;
      Object objString = (Object)strValue;

      return objString;
    }
 }

Solution

  • Just generally speaking: You cannot assume that every conversion is lossless, especially ToString is normally quite the opposite, unless your object is very simple you will not be able to reconstruct it.

    Simple example, convert number to its digit-sum: 2584 -> 19, the backwards conversion is indeterminate because the unique mapping is one-way only. There are quite a lot of numbers with a digit sum of 19 but 2584 has only one digit sum.