In the resources of your Window
/UserControl
/? you have to create an ObjectDataProvider
like:
<ObjectDataProvider x:Key="MovieDataProvider" MethodName="GetValues" ObjectType="{x:Type namespace:MovieType}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="namespace:MovieType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
To use it as itemssource of your ComboBox
you have to do the following:
ItemsSource="{Binding Source={StaticResource MovieDataProvider}}"
If you want to display a custom value you can modify the ItemTemplate of your ComboBox
like:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={converters:MovieDisplayConverter}}"/>
</DataTemplate>
</ComboBox>
The MovieDisplayConverter can look like the following if you want to return custom values:
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());
}
}
If you want the description-attribute of your enum-values in the ComboBox
replace the convert-method of the above converter with the following:
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;
}