0

I have an enum

public enum LookupTypes
{
    [StringValue("UNIV")]
    University,
    [StringValue("COUR")]
    Course}

How can i bind this in dropdownlist with UNIV as value and University as Text

c#/WPF

JaseemAmeer
  • 107
  • 2
  • 15
  • What language/framework? C# I guess, but WPF or WinForms? – TWiStErRob Jan 05 '14 at 13:54
  • possibly duplicate : http://stackoverflow.com/questions/61953/how-do-you-bind-an-enum-to-a-dropdownlist-control-in-asp-net , http://stackoverflow.com/questions/3098623/how-to-bind-enum-types-to-the-dropdownlist – Sachin Jan 05 '14 at 14:03

1 Answers1

0

You'll need a few converters:

  • To display enum list ("University", "Course"), you'll need EnumValuesConverter, it's wrapping "enumType.getValues()"
  • Then you can use the provided extension method StringValue() to get the attribute's value.
  • Or use a converter EnumToStringValueConverter which does the same, to display the value on the UI (see Labels)
  • If by "with UNIV as value" you meant, combo.SelectedValue to be string UNIV tough luck, because SelectedValuePath doesn't handle functions, only properties.

Try this beast:

<Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:app="clr-namespace:WpfApplication1"
            Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <app:EnumValuesConverter x:Key="enumValuesConverter" />
        <app:EnumToStringValueConverter x:Key="enumToStringValueConverter" />
    </Window.Resources>
    <StackPanel x:Name="context">
        <ComboBox x:Name="combo"
                      ItemsSource="{Binding Source={x:Type app:LookupTypes}, Mode=OneTime, Converter={StaticResource enumValuesConverter}}"
                      SelectedItem="{Binding EnumProp, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding}" ToolTip="{Binding Converter={StaticResource enumToStringValueConverter}}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <Label Content="{Binding EnumProp}" ContentStringFormat="Selected Enum: {0}" />
        <Label Content="{Binding EnumProp, Converter={StaticResource enumToStringValueConverter}}" ContentStringFormat="Selected StringValue: {0}" />
        <Button Click="Button_Click" Content="Alert enum" />
    </StackPanel>
</Window>

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            context.DataContext = new MyViewModel {
                EnumProp = LookupTypes.Course
            };
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            LookupTypes type = (LookupTypes)combo.SelectedItem;
            MessageBox.Show(string.Format("Are you sure you want to use {0} ({1}) as lookup type?", type, type.StringValue()));
        }
    }

    [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public sealed class StringValueAttribute : Attribute {
        public StringValueAttribute(string stringValue) {
            StringValue = stringValue;
        }
        public string StringValue { get; private set; }
    }

    public static class StringValueExtensions {
        public static string StringValue(this Enum This) {
            System.Reflection.FieldInfo fieldInfo = This.GetType().GetField(This.ToString());
            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
            return attribs.Length == 0 ? null : attribs[0].StringValue;
        }
    }

    public enum LookupTypes {
        [StringValue("UNIV")]
        University,
        [StringValue("COUR")]
        Course
    }

    class MyViewModel {
        public LookupTypes EnumProp { get; set; }
    }

    [ValueConversion(typeof(Enum), typeof(string[]))]
    public class EnumValuesConverter : IValueConverter {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (value == null) return Binding.DoNothing;
            return Enum.GetValues((Type)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
        #endregion
    }

    [ValueConversion(typeof(Enum), typeof(string))]
    public class EnumToStringValueConverter : DependencyObject, IValueConverter {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (value == null) return Binding.DoNothing;
            return ((Enum)value).StringValue();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
        #endregion
    }
}
TWiStErRob
  • 44,762
  • 26
  • 170
  • 254