IValueConverter的最佳做法是什么?

  • IValueConverter的最佳做法是什么?
  • 可以将Exception放在Convert方法中,还是应该返回“something”?

这是一个例子:

[ValueConversion(typeof(float), typeof(String))] public class PercentConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null || string.IsNullOrEmpty(value.ToString())) return string.Empty; if (value is float) //Edited to support CultureInfo.CurrentCulture, return string.Format(culture, "{0:n}{1}", ((float)value) * 100, "%"); //** Is it ok to put Exception here or should I return "something" here? ** throw new Exception("Can't convert from " + value.GetType().Name + ". Expected type if float."); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException("Converting back is not implemented in " + this.GetType()); } } 

如果转换失败(格式错误的值,类型……),请返回DependencyProperty.UnsetValue 。

它表示转换器没有产生任何值,并且绑定使用FallbackValue(如果可用)或默认值。

此外,您应该将具有特定于文化的转换或不变转换的数据转换为安全的一面。

我个人建议使用单例转换器。 然后您不必在每个使用站点创建一个实例,但可以像这样引用转换器:

 Converter={x:Static SomeNamespace:SomeConverter.Instance} 

您在解析字符串时忽略了CultureInfo

总是考虑传递的文化信息,否则它将始终在Thread的CurrentCulture上工作。

我可以给出一些像“7.34,123”这样的东西作为输入,你的代码会起作用吗?