1

I need to bind an enum to a combobox that is inside a DataGridTemplateColumn, but only some of the options that the enum has.
Example:
Enum options: Unknow, One, Two, Three, Four, All
Bindable ones: One, Two, Three, Four

Any way to do this?
Many thanks.

Best regards

3 Answers 3

5

I have a value converter that I use for this. It's geared toward binding to a property of the enum type which would be use for both the ItemsSource and SelectedItem:

<ComboBox ItemsSource="{Binding Path=Day, Converter={StaticResource EnumToListConverter}, ConverterParameter='Monday;Friday'}" SelectedItem="{Binding Day}"/>

It can also be used by directly referencing the enum:

<ComboBox ItemsSource="{Binding Source={x:Static sys:DayOfWeek.Sunday}, Converter={StaticResource EnumToListConverter}, ConverterParameter='Monday;Friday'}" Grid.Column="2"/>

Here's the converter code:

public class EnumToListConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is Enum))
            return null;

        string filters = parameter == null ? String.Empty : parameter.ToString();
        IEnumerable enumList;
        string[] splitFilters = filters != null ? filters.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { };
        List<string> removalList = new List<string>(splitFilters);
        Type enumType = value.GetType();
        Array allValues = Enum.GetValues(enumType);
        try
        {
            var filteredValues = from object enumVal in allValues
                                 where !removalList.Contains(Enum.GetName(enumType, enumVal))
                                 select enumVal;
            enumList = filteredValues;
        }
        catch (ArgumentNullException)
        {
            enumList = allValues;
        }
        catch (ArgumentException)
        {
            enumList = allValues;
        }
        return enumList;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
0

Copy the enums you wish to bind to an array and then bind to the array.

0

May be this kink can help you

Databinding an enum property to a ComboBox in WPF

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.