【问题标题】:IValue Converter: ConvertBack - String to ObjectIValue 转换器:ConvertBack - 字符串到对象
【发布时间】:2011-08-17 21:05:37
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf data-binding object ivalueconverter


    【解决方案1】:

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

    简单示例,将数字转换为其数字和:2584 -> 19,向后转换是不确定的,因为唯一映射只是单向的。 19 的数字总和相当多,但 2584 的数字总和只有一位。

    【讨论】:

    • 很有趣,所以这看起来像是你会避免的。
    • 不一定,要看你是否需要反向转换。
    • 那么您是否同意 infensus 并避免使用 valueconverter 来执行此操作?
    • 是的,我必须进行反向转换。
    • 你到底想做什么?
    【解决方案2】:

    尝试一些类似的东西:

    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;
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 不是我,是别人创造的模型。他创建了这个 BasePar 类来读取不同的类型。
      猜你喜欢
      • 1970-01-01
      • 2011-05-31
      • 2014-09-17
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      相关资源
      最近更新 更多