【问题标题】:Passing current combobox item to Converter using converterparamter使用转换器参数将当前组合框项传递给转换器
【发布时间】:2018-02-13 11:06:53
【问题描述】:

我有一个枚举描述转换器

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

我喜欢将当前组合框项作为 ConverterParameter 传递给转换器

<ComboBox Name="test" Grid.Column="1" Grid.Row="2" VerticalAlignment="Center" IsReadOnly="True" >
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter},ConverterParameter=Value}"/>
                        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>

但是当我尝试绑定错误时,Value 以字符串“Value”的形式出现。有什么方法可以传递当前项目吗?

【问题讨论】:

  • 我不清楚为什么你需要一个转换器参数。看起来您正在尝试在存在时生成 [Description] 文本,否则生成枚举名称。枚举值应作为value 参数进入Convert()。为什么在这种情况下需要额外的parameter
  • 之前我使用的是string parameterString = parameter as string; var desc = (value.GetType().GetField(parameterString) ; 当我得到参数值时,我可以避免调用 Enum.GetName(value.GetType(), value);

标签: c# wpf combobox ivalueconverter


【解决方案1】:

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

value.GetType().GetField(parameterString)

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

你可以完全摆脱parameterString。单个枚举值的字符串表示始终与该值的字段名称匹配(或者,在多个枚举元素具有相同值的情况下,它将匹配 equivalent 值的字段名称。

【讨论】:

  • “单数枚举值的字符串表示总是与字段名匹配”——并非总是如此。例如,尝试获取 System.Windows.Forms.MessageBoxIcon 的每个枚举值的字符串表示形式(相同的值具有不同的名称)
  • @ASh 好点。我应该说它匹配 equivalentequal 值的字段名称。已编辑。
猜你喜欢
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2011-08-07
  • 1970-01-01
  • 2022-01-19
  • 2014-01-26
相关资源
最近更新 更多