嗨,我使用依赖对象将我的组合框与枚举绑定。我搜索并发现这个解决方案对于 MVVM 来说非常优雅,
我的xml是
<ComboBox SelectedItem="{Binding Color,Mode=TwoWay}"
l:EnumHelper.Enum="{x:Type l:MyEnum }"></ComboBox>
我的依赖对象是
public class EnumHelper : DependencyObject
{
public static Type GetEnum(DependencyObject obj)
{
return (Type)obj.GetValue(EnumProperty);
}
public static void SetEnum(DependencyObject obj, string value)
{
obj.SetValue(EnumProperty, value);
}
// Using a DependencyProperty as the backing store for Enum. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnumProperty =
DependencyProperty.RegisterAttached("Enum", typeof(Type), typeof(EnumHelper), new PropertyMetadata(null, OnEnumChanged));
private static void OnEnumChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as ItemsControl;
if (control != null)
{
if (e.NewValue != null)
{
var _enum = Enum.GetValues(e.NewValue as Type);
control.ItemsSource = _enum;
}
}
}
}
我想知道我是否必须阅读枚举描述并使用依赖对象将它们转换回来,我该如何扩展这个帮助类。