使用converterparamter将当前组合框项目传递给Converter

时间:2018-02-13 11:06:53

标签: c# wpf combobox ivalueconverter

我有一个枚举说明转换器

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:com/renfe/cme/recursos/spring/applicationContext-*.xml</param-value>
        <description>Spring files location</description>
    </context-param>

我想将当前的组合框项目作为ConverterParameter传递给转换器

public class EnumDescriptionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //// parameter need current item, but null or "Value"
        if (Enum.IsDefined(value.GetType(), value) == false)
            return System.Windows.DependencyProperty.UnsetValue;

        string parameterString = Enum.GetName(value.GetType(), value);  
        if (parameterString == null)
            return System.Windows.DependencyProperty.UnsetValue;

        var desc = (value.GetType().GetField(parameterString).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute);
        if (desc != null)
            return desc.Description;
        else
            return parameter.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是当我尝试绑定获取错误时,Value将作为字符串“Value”出现。有没有办法传递当前项目?

1 个答案:

答案 0 :(得分:0)

您不需要转换器参数。只需更换:

value.GetType().GetField(parameterString)

value.GetType().GetField(value.ToString())

你可以完全摆脱parameterString。单数枚举值的字符串表示形式始终与该值的字段名称匹配(或者,如果多个枚举元素具有相同的值,则它将匹配等效值的字段名称)。 / p>

相关问题