带有枚举和空值的组合框

问题描述 投票:0回答:1

我有一个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具有另一个值-一个空值。因此,我无法选择任何枚举值并取消选择先前选择的值。

如何?

c# wpf enums nullable markup-extensions
1个回答
0
投票

您可以将ItemsSource设置为要添加另一个CompositeCollectionstring

<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>
© www.soinside.com 2019 - 2024. All rights reserved.