2015-11-05 62 views
1

我在WPF應用程序中使用caliburn微框架。 我需要將此枚舉綁定到組合框。MVVM將枚舉綁定到Combobox

考慮一個ViewModel以下枚舉:

public enum MovieType 
{ 
    [Description("Action Movie")] 
    Action, 
    [Description("Horror Movie")] 
    Horror 
} 
  1. 我怎麼能這個枚舉綁定到一個組合框?
  2. 是否有可能顯示枚舉值在 組合框中的枚舉值?
  3. 我可以爲此實現IvalueConverter嗎?
+1

這些問題全部3被處理在我上面發佈的鏈接中。 –

回答

2

在您的資源Window/UserControl /?你必須創建一個ObjectDataProvider這樣的:如果你想顯示自定義的值,你可以修改的ItemTemplate

ItemsSource="{Binding Source={StaticResource MovieDataProvider}}" 

<ObjectDataProvider x:Key="MovieDataProvider" MethodName="GetValues" ObjectType="{x:Type namespace:MovieType}"> 
    <ObjectDataProvider.MethodParameters> 
     <x:Type Type="namespace:MovieType"/> 
    </ObjectDataProvider.MethodParameters> 
</ObjectDataProvider> 

要使用它作爲的ItemsSource您的ComboBox你必須做到以下幾點您ComboBox這樣的:

<ComboBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding Converter={converters:MovieDisplayConverter}}"/> 
    </DataTemplate> 
</ComboBox> 

的MovieDisplayConverter可以像下面的,如果你想返回定製VA梅毒:

internal class MovieDisplayConverter : MarkupExtension, IValueConverter 
    { 
     private static MovieDisplayConverter converter; 

     public MovieDisplayConverter() 
     { 

     } 

     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (value is MovieType) 
      { 


       switch ((MovieType)value) 
       { 
        case MovieType.Action: 
         return "Action Movie"; 
        case MovieType.Horror: 
         return "Horror Movie"; 
        default: 
         throw new ArgumentOutOfRangeException("value", value, null); 
       } 
      } 
      return value; 
     } 

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

     public override object ProvideValue(IServiceProvider serviceProvider) 
     { 
      return converter ?? (converter = new MovieDisplayConverter()); 
     } 
    } 

如果你想在ComboBox您的枚舉值的描述​​屬性用以下內容替換上述轉換器中的轉換法:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      if (value is MovieType) 
      { 
       FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); 
       if (fieldInfo != null) 
       { 
        object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true); 
        if (attributes.Length > 0) 
        { 
         return ((DescriptionAttribute)attributes[0]).Description; 
        } 
       } 
      } 
      return value; 
     } 
+0

嘿,你遲到了1分鐘! :) – Jose