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

Paulo
  • 609
  • 1
  • 11
  • 27

3 Answers3

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();
    }
}
John Bowen
  • 24,213
  • 4
  • 58
  • 56
0

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

Allan
  • 449
  • 5
  • 11
0

May be this kink can help you

Databinding an enum property to a ComboBox in WPF

Community
  • 1
  • 1
Kishore Kumar
  • 21,449
  • 13
  • 81
  • 113