I have a ComboBox
that is filled from the values of an enumeration:
<ComboBox ItemsSource="{utils:Enumerate {x:Type models:MyEnum}}"
SelectedItem="{Binding SelectedEnumValue, Converter={StaticResource EnumToStringConverter}}" />
That uses utils:Enumerate
, an extension class, to get the values of the enum
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;
}
}
That works great and displays all the possible values of an enum in a combobox. It also contains nice readable texts instead of enum values like NotReleased
.
But I want the comboxbox to have another value - an empty one. So I can select none of the enum values and deselect previously selected values.
How?
You could set the ItemsSource
to a CompositeCollection
to which you add another 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>
Replace System.Runtime
with mscorlib
in the namespace declaration if you target the .NET Framework.
Or you could add another string
to the string[]
returned from your ProvideValue
method.