什么是的IValueConverter最佳做法? [英] What is best practise for IValueConverter?

查看:171
本文介绍了什么是的IValueConverter最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 什么是最好的做法的IValueConverter
  • 它是确定把异常的转换方法,还是应该回归东西?

下面是一个例子:

  [ValueConversion(typeof运算(浮点),typeof运算(字符串))
公共类PercentConverter:的IValueConverter
{
    公共对象转换(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
    {
        如果(价值== NULL || string.IsNullOrEmpty(value.ToString()))
            返回的String.Empty;

        如果(值是浮点数)//编辑,支持CultureInfo.CurrentCulture,
            返回的String.Format(文化,{0:N} {1},((浮点)值)* 100,%);

        // **它是确定将异常这里还是我应该回到东西吗? **
        抛出新的异常(+ value.GetType()名+无法从转换。预期的类型,如果浮动。);
    }

    公共对象ConvertBack(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
    {
        抛出新NotSupportedException异常(转换回是不是在执行+ this.GetType());
    }
}
 

解决方案

如果您无法转换(格式不正确的值,类型,...),返回<一href="http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.unsetvalue.aspx">DependencyProperty.UnsetValue.

有表示该转换器产生没有价值,而且结合使用FallbackValue,如果有的话,或默认值,而不是

此外,你应该转换数据和区域性特定转换或转换不变的是在安全方面。

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

解决方案

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.

这篇关于什么是的IValueConverter最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆