我有一个ComboBox
,该值由枚举的值填充:
<ComboBox ItemsSource="{utils:Enumerate {x:Type models:MyEnum}}"
SelectedItem="{Binding SelectedEnumValue, Converter={StaticResource EnumToStringConverter}}" />
使用扩展类utils:Enumerate
来获取枚举的值
public sealed class EnumerateExtension : MarkupExtension
{
public Type Type { get; set; }
public EnumerateExtension(Type type)
{
Type = type;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var names = Enum.GetNames(Type);
string[] values = new string[names.Length];
for (int i = 0; i < names.Length; i++)
{
values[i] = StringResources.Get(names[i]); //translating the enum value into a readable text
}
return values;
}
}
效果很好,并在组合框中显示了枚举的所有可能值。它还包含漂亮的可读文本,而不是像NotReleased
这样的枚举值。
但是我希望comboxbox具有另一个值-一个空值。因此,我无法选择任何枚举值并取消选择先前选择的值。
如何?
您可以将ItemsSource
设置为要添加另一个CompositeCollection
的string
:
<ComboBox SelectedItem="...">
<ComboBox.ItemsSource>
<CompositeCollection xmlns:s="clr-namespace:System;assembly=System.Runtime">
<s:String>(empty)</s:String>
<CollectionContainer Collection="{Binding Source={utils:Enumerate {x:Type models:MyEnum}}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
</ComboBox>