将枚举属性数据绑定到WP中的ComboBox
将枚举属性数据绑定到WP中的ComboBox
以以下代码为例:
public enum ExampleEnum { FooBar, BarFoo } public class ExampleClass : INotifyPropertyChanged { private ExampleEnum example; public ExampleEnum ExampleProperty { get { return example; } { /* set and notify */; } } }
我想把属性ExampleProperty数据绑定到ComboBox上,以便它显示选项\"FooBar\"和\"BarFoo\",并以TwoWay模式工作。最理想的是,我希望我的ComboBox定义看起来像这样:
目前,我在Window中手动绑定时,为ComboBox.SelectionChanged和ExampleClass.PropertyChanged事件安装了处理程序。
是否有更好的或某种规范的方法?通常会使用转换器,那么如何用正确的值填充ComboBox?我现在甚至不想开始国际化。
编辑
因此,一个问题得到了回答:如何用正确的值填充ComboBox。
通过ObjectDataProvider从静态Enum.GetValues方法检索Enum值作为字符串列表:
这可以用作我的ComboBox的ItemsSource:
admin 更改状态以发布 2023年5月21日
在ViewModel中,你可以拥有:
public MyEnumType SelectedMyEnumType { get { return _selectedMyEnumType; } set { _selectedMyEnumType = value; OnPropertyChanged("SelectedMyEnumType"); } } public IEnumerableMyEnumTypeValues { get { return Enum.GetValues(typeof(MyEnumType)) .Cast (); } }
在XAML中,ItemSource
绑定到MyEnumTypeValues
,SelectedItem
绑定到SelectedMyEnumType
。
您可以创建自定义的标记扩展。
使用示例:
enum Status { [Description("Available.")] Available, [Description("Not here right now.")] Away, [Description("I don't have time right now.")] Busy }
在您的XAML文件的顶部:
xmlns:my="clr-namespace:namespace_to_enumeration_extension_class
然后...
实现如下...
public class EnumerationExtension : MarkupExtension { private Type _enumType; public EnumerationExtension(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); EnumType = enumType; } public Type EnumType { get { return _enumType; } private set { if (_enumType == value) return; var enumType = Nullable.GetUnderlyingType(value) ?? value; if (enumType.IsEnum == false) throw new ArgumentException("Type must be an Enum."); _enumType = value; } } public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI { var enumValues = Enum.GetValues(EnumType); return ( from object enumValue in enumValues select new EnumerationMember{ Value = enumValue, Description = GetDescription(enumValue) }).ToArray(); } private string GetDescription(object enumValue) { var descriptionAttribute = EnumType .GetField(enumValue.ToString()) .GetCustomAttributes(typeof (DescriptionAttribute), false) .FirstOrDefault() as DescriptionAttribute; return descriptionAttribute != null ? descriptionAttribute.Description : enumValue.ToString(); } public class EnumerationMember { public string Description { get; set; } public object Value { get; set; } } }