我在WPF应用程序中使用了caliburn micro框架。 我需要将这个枚举绑定到一个组合框。
考虑在ViewModel中跟随枚举:
public enum MovieType
{
[Description("Action Movie")]
Action,
[Description("Horror Movie")]
Horror
}
答案 0 :(得分:2)
在Window
/ UserControl
/的资源中?你必须创建一个ObjectDataProvider
,如:
<ObjectDataProvider x:Key="MovieDataProvider" MethodName="GetValues" ObjectType="{x:Type namespace:MovieType}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="namespace:MovieType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
要将其用作ComboBox
的项目来源,您必须执行以下操作:
ItemsSource="{Binding Source={StaticResource MovieDataProvider}}"
如果要显示自定义值,可以修改ComboBox
的ItemTemplate,如:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={converters:MovieDisplayConverter}}"/>
</DataTemplate>
</ComboBox>
如果要返回自定义值,MovieDisplayConverter可能如下所示:
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
中枚举值的description-attribute替换上述转换器的convert-method,请执行以下操作:
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;
}