0

我可以将工作从对象转换为文本框。但是我在转换时有点茫然。非常感谢任何线索或帮助。

 [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;
    }
 }
4

3 回答 3

3

一般而言:您不能假设每次转换都是无损的,尤其ToString是通常情况正好相反,除非您的对象非常简单,否则您将无法重建它。

简单的例子,将 number 转换为其 digit-sum: 2584 -> 19,反向转换是不确定的,因为唯一映射只是单向的。有相当多的数字有一个数字和192584只有一个数字和。

于 2011-05-03T17:13:34.867 回答
1

确实如 HB 所说,你为什么要在文本框对象和字符串之间进行转换?似乎您可能需要查看您的设计 - 它被称为转换器是有原因的!如果您真的想这样做,请查看类序列化 - 序列化为 MemoryStream 并反序列化为对象。您也可以从字符串反序列化(http://stackoverflow.com/questions/2347642/deserialize-from-string-instead-textreader),但是既然您不想显示那种字符串,为什么还要麻烦呢?如果出于某种疯狂的原因您确实想要序列化为字符串,您可以将内存位置设置为 0 并将内存流传递给 StreamReader,然后调用 StreamReader.ReadToEnd().ToString()。

于 2011-05-03T17:28:59.800 回答
1

尝试一些类似的东西:

var textBoxValue = value as string;
if(textBoxValue != null) {
    // Create BasePar instance, setting the textBoxValue as a property value or whatever and return it
}
return DependencyProperty.UnsetValue;
于 2011-05-03T16:39:53.623 回答