c# - 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?
解决方案
您可以将ItemsSource
a设置为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
到string[]
您的方法返回的内容中ProvideValue
。
推荐阅读
- mysql - 用户定义的函数只返回 NULL
- google-apps-script - 基于谷歌表格中的多行循环脚本
- sql - 存储过程运行了多天......我的语法是否有问题导致它无限循环?
- php - 根据一对多关系的值对集合进行排序
- sql-server - HashiCorp 根数据库凭证轮换与 SQL Server
- node.js - 如何在 mongodb 中找到整数值的 $regex?
- angular - 为什么 Angular 6 在“e2e/app”文件夹中生成我的服务?
- javascript - 现代 ES6 javascript 类的方法的局部临时变量
- node.js - 尝试将 https 路径拉入 ffmpeg 以用于在 aws ec2 上运行的 node-js 失败,并显示“输入文件不存在”
- php - PHP 突然开始无法执行 shell 命令