IValueConverter 的最佳实践是什么?
IValueConverter 的最佳实践是什么:是可以将 Exception 放入 Convert 方法中还是应该返回“某些内容”?
这是一个例子:
[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());
}
}
What is best practise for IValueConverter: Is it ok to put Exception in Convert method or should it return "something"?
Here is an example:
[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());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果转换失败(格式错误的值、类型等),请返回 DependencyProperty.UnsetValue。
它指示转换器未生成任何值,并且绑定使用 FallbackValue(如果可用)或默认值。
此外,为了安全起见,您应该使用特定于区域性的转换或不变转换来转换数据。
If you fail to convert (malformed values, types, ...), return DependencyProperty.UnsetValue.
It indicates that the converter produced no value and that the binding uses the FallbackValue, if available, or the default value instead.
Also, you should convert data with culture-specific conversion or invariant conversions to be on the safe side.
我个人建议使用单例转换器。然后,您不必在每个使用站点创建实例,但可以像这样引用转换器:
I personally recommend using singleton converters. Then you don't have to create an instance at every usage site, but can reference the converter like this:
您在解析字符串时忽略了
CultureInfo
。始终考虑传递的区域性信息,否则它将始终在线程的 CurrentCulture 上工作。
我可以提供诸如“7.34,123”之类的内容作为输入,您的代码可以工作吗?
You've ignored
CultureInfo
while parsing the string.Always take in to account the culture info passed otherwise it would always work on Thread's CurrentCulture.
I could give some thing like "7.34,123" as input, would your code work?