首页 > 解决方案 > ComboBox with enumeration and null value

问题描述

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?

标签: c#wpfenumsnullablemarkup-extensions

解决方案


您可以将ItemsSourcea设置为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>

如果您以 .NET Framework 为目标,请在命名空间声明中替换System.Runtime为。mscorlib

或者您可以将另一个添加stringstring[]您的方法返回的内容中ProvideValue


推荐阅读