2010-05-01 68 views
0

我需要将枚举绑定到DataGridTemplateColumn中的组合框,但只包含枚举所具有的一些选项。
例子:
枚举选项: 不明一个两个所有
可绑定的:一个两个四个将枚举数据绑定到WPF中的ComboBox,筛选一些枚举

任何方式 做这个?
非常感谢。

致以问候

回答

5

我有我使用这个值转换器。它向着结合这将是使用了两种的ItemsSource和的SelectedItem枚举类型的属性面向:

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

它还可以通过直接引用枚举使用:

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

这里的转换器代码:

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

将您希望绑定到数组的枚举复制,然后绑定到数组。