IValueConverter的最佳做法是什么?

Ami*_*aei 6 .net c# wpf xaml

  • 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*dek 14

如果您无法转换(格式错误的值,类型......),请返回DependencyProperty.UnsetValue.

它表示转换器未生成任何值,并且绑定使用FallbackValue(如果可用)或默认值.

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


Mat*_*ský 6

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

Converter={x:Static SomeNamespace:SomeConverter.Instance}
Run Code Online (Sandbox Code Playgroud)