转换器显示一个枚举的描述,并转换回枚举值从组合框在WPF选择一个项目 [英] Converter to show description of an enum, and convert back to enum value on selecting an item from combo box in wpf

查看:770
本文介绍了转换器显示一个枚举的描述,并转换回枚举值从组合框在WPF选择一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个枚举在我的组合框争取值。 我想写一个转换器,将显示所选择的枚举值的说明。而且,选择的时候,它会返回枚举值。

I am using an enum to enlist values in my combobox. I want to write a converter that would show the "description" of the selected enum value. And, when selected, it would return the enum value.

大多数网上还没有实现ConvertBack()方法的转换器(这就是为什么我在这里发帖)。

Most of the converters online have not implemented the ConvertBack() method (which is why I am posting here).

在此先感谢。

推荐答案

下面是ConvertBack方式:

Here is ConvertBack method:

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    return value;
    // return Enum.ToObject(targetType, value);
}

全部转换code:

public class EnumConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return DependencyProperty.UnsetValue;

        return GetDescription((Enum)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.ToObject(targetType, value);
    }

    public static string GetDescription(Enum en)
    {
        Type type = en.GetType();
        MemberInfo[] memInfo = type.GetMember(en.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attrs != null && attrs.Length > 0)
            {
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        return en.ToString();
    }
}

修改

下面是我的组合框的XAML:

Here is my ComboBox XAML:

<ComboBox ItemsSource="{Binding SampleValues}" 
          SelectedItem="{Binding SelectedValue, Converter={StaticResource enumConverter}}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., Converter={StaticResource enumConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

编辑2:

我本来有一个不正确的XAML,我是有约束力的,而不是<$ C 的SelectedValue ComboBox.SelectedIndex , $ C> ComboBox.SelectedItem 。这就是为什么我不得不使用 Enum.ToObject 在我的 ConvertBack 方法。通过调试固定的XAML和运行样品后,我意识到我可以只返回 ConvertBack 的方法,使价值本身就是枚举键入

I originally had an incorrect XAML, I was binding SelectedValue to ComboBox.SelectedIndex, instead of ComboBox.SelectedItem. That's why I had to use Enum.ToObject in my ConvertBack method. After fixing the XAML and running the sample through the debugger I realized I could just return value from ConvertBack method, cause the value itself is of Enum type.

这篇关于转换器显示一个枚举的描述,并转换回枚举值从组合框在WPF选择一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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