How to populated WPF comboboxes with generic enum to List<string> function

105 views Asked by At

I would like to populate WPF combobox (and other similar controls) with the geniric enum to List<string> below:

How do I call it in XAML?

public class ToList<TEnum> : List<string> where TEnum : struct, Enum
{
    public static ToList()
    {
        foreach (TEnum e in Enum.GetValues(typeof(TEnum)))
        {
            // Skips some values (TEnum.NotDefined)
            if (e.Equals((TEnum)Enum.ToObject(typeof(TEnum), -1))) continue;
            
            // GetDescription() is an extension method based on the [Description] attribute
            Add(e.GetDescription());
        }
     }
}

Example with hardcoded enum

XAML with MyEnum a property of the view model

<converters:MyEnumToStringConverter x:Key="MyEnumToString"/>
...
<ComboBox ItemsSource="{StaticResource MyEnumList}" SelectedItem="{Binding MyEnum, Converter=MyEnumToString}">

Non-generic enum-to-List method

public class MyEnumList : List<string>
{
    public MyEnumList()
    {
        foreach (MyEnum myEnum in Enum.GetValues(typeof(MyEnum)))
        {
            if (myEnum == myEnum.NotDefined) continue;

            Add(myEnum.GetDescription());
        }
    }   
}

Value converter (with culture localization potentially in the future). Can I pass the enum as targetType or parameter?

public class MyEnumToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => ((MyEnum)value).GetDescription();

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing;
}

Basically, I don't want to hard-code the example above for MyEnumA, MyEnumB and so on.

Thanks for any insights :-)

0

There are 0 answers