简体   繁体   English

IValueConverter 的最佳实践是什么?

[英]What is best practise for IValueConverter?

What is best practise for IValueConverter : Is it ok to put Exception in Convert method or should it return "something"? IValueConverter的最佳实践是什么:可以将异常放入 Convert 方法中还是应该返回“某物”?

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());
    }
}

If you fail to convert (malformed values, types, ...), return DependencyProperty.UnsetValue .如果您无法转换(格式错误的值、类型等),请返回DependencyProperty.UnsetValue

It indicates that the converter produced no value and that the binding uses the FallbackValue, if available, or the default value instead.它表示转换器没有产生任何值,并且绑定使用 FallbackValue(如果可用)或默认值。

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:然后您不必在每个使用站点都创建实例,但可以像这样引用转换器:

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

You've ignored CultureInfo while parsing the string.您在解析字符串时忽略了CultureInfo

Always take in to account the culture info passed otherwise it would always work on Thread's CurrentCulture.始终考虑传递的文化信息,否则它将始终适用于 Thread 的 CurrentCulture。

I could give some thing like "7.34,123" as input, would your code work?我可以输入“7.34,123”之类的东西,你的代码可以工作吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM