您可以使用ivalueConverter执行此操作:
XAML:
<ComboBox Width="100" Height="30" ItemsSource="{Binding GenreSource,Converter={StaticResource ec}}"
SelectedItem="{Binding SelectedGenre, Mode=TwoWay, Converter={StaticResource gc}}"></ComboBox>
public class DemoViewModel : ViewModel
{
public DemoViewModel()
{
}
public Type GenreSource
{
get
{
return typeof(Genres);
}
}
private Genres _SelectedGenre;
public Genres SelectedGenre
{
get { return _SelectedGenre; }
set
{
_SelectedGenre = value;
OnPropertyChanged("SelectedGrape");
}
}
}
从枚举转换为组合框的列表:
public class EnumListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var enumType = (Type)value;
var names = new List<string>();
foreach (var fieldInfo in enumType.GetFields(BindingFlags.Static | BindingFlags.Public))
{
names.Add(fieldInfo.Name);
}
return names;
}
并从字符串转换回列表:
public class GenreConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (Views.Genres)Enum.Parse(typeof(Views.Genres), value.ToString(), false);
}
}
您可以将完整的类型名传递给genrecoverter,使其成为任何枚举的泛型。