views:

65

answers:

3

Hello everyone.

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

A: 

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

Allan
A: 

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