Pull to refresh

Привязка enum к ComboBox в C# WPF

Существует множество вариантов решения задачи привязки переменной типа enum к ComboBox с возможностью выбора значения из списка.

Предлагаю одно, на мой взгляд, самое удобное решение.

Есть список enum.

public enum TypeValue
    {
        [Description("Нет")]
        None,
        [Description("Величина")]
        Value,
        [Description("Ячейка")]
        Cell,
        [Description("Столбец")]
        Column,
        [Description("Формула")]
        Formula,
    }

Необходимо для переменной типа ColumnParse выбирать ValueType с привязкой к ComboBox в окне WPF.

image

Привязывать будем переменную класса ColumnParse.

    public class ColumnParse
    {
        public string Value { set; get; }
        public TypeValue ValueType { set; get; }    
    }

Во-первых, необходимо получить список Description всех значений enum.

public class EnumToItemsSource : MarkupExtension
    {
        private readonly Type _type;

        public EnumToItemsSource(Type type)
        {
            _type = type;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _type.GetMembers().SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>()).Select(x => x.Description).ToList();
        }
    }

Далее привяжем список Descriptions к ComboBox.

<ComboBox ItemsSource="{Binding Source={local:EnumToItemsSource {x:Type local:TypeValue}}}" />

Теперь создадим переменную Var_parser, которую мы привяжем к DataContext окна.

public partial class MainWindows : Window
    {
        public MainWindows()
        {
            InitializeComponent();
            ColumnParse Var_parser = new ColumnParse();
            this.DataContext = Var_parser;
        }
    }

Привязка переменной к ComboBox.

Теперь для того, чтобы можно было менять значение ValueType у Var_parser нужно привязать ValueType к списку ComboBox, который мы описали выше.

<ComboBox SelectedValue="{Binding ValueType, Converter={StaticResource EnumConverter},  ConverterParameter={x:Type local:TypeValue}}" ItemsSource="{Binding Source={local:EnumToItemsSource {x:Type local:TypeValue}}}" />

Конвертер EnumConverter, который переводит enum значение в его Description и обратно.

public class EnumConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            if (value == null) return "";
            foreach (var one in Enum.GetValues(parameter as Type))
            {
                if (value.Equals(one))
                    return one.GetDescription();
            }
            return "";
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            if (value == null) return null;
            foreach (var one in Enum.GetValues(parameter as Type))
            {
                if (value.ToString() == one.GetDescription())
                    return one;
            }
            return null;
        }
    }
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.