2010-05-01 150 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

將您希望綁定到數組的枚舉複製,然後綁定到數組。