【问题标题】:ComboBox with enumeration and null value具有枚举和空值的组合框
【发布时间】:2020-03-25 12:23:37
【问题描述】:

我有一个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 这样的枚举值。

但我希望组合框有另一个值 - 一个空值。所以我可以不选择任何枚举值并取消选择以前选择的值。

怎么做?

【问题讨论】:

    标签: c# wpf enums nullable markup-extensions


    【解决方案1】:

    您可以将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>
    

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

    或者您可以将另一个string 添加到您的ProvideValue 方法返回的string[]

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2015-08-03
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多