ComboBox 绑定到枚举类型的值,同时还具有“空白”字段。 入口?
如果我将 WinForms ComboBox 绑定到枚举类型的值,即
combo1.DropDownStyle = ComboBoxStyle.DropDownList;
combo1.DataSource = Enum.GetValues(typeof(myEnumType));
谁知道我如何实现相同的结果,同时,除了与每个枚举值匹配的条目之外,我还可以有一个表示没有选择的空白条目?
我不能简单地向枚举类型添加特殊值,因为这必须灵活地处理任何枚举类型。
我很感激你的帮助。
编辑:我应该明确表示我想要绑定实际的枚举值而不是它们的名称。 如果实际的枚举值已绑定,则 ComboBox 负责调用其 ToString() 来获取要显示的文本。
If I bind a WinForms ComboBox to an enum type's values, i.e.
combo1.DropDownStyle = ComboBoxStyle.DropDownList;
combo1.DataSource = Enum.GetValues(typeof(myEnumType));
Who knows how I could achieve the same result, while, in addition to entries matching each enum value, I can also have a blank entry representing no selection?
I cannot simply add a special value to the enum type because this must be flexible to deal with any enum type.
I'd appreciate your help.
Edit: I should make clear that I want to bind the actual enum values and not their names. If the actual enum values are bound, the ComboBox takes care of calling their ToString() to get the text to display.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定你们是否已经尝试过您发布的所有代码,但是您无法添加数据绑定组合框的项目。 这是winforms,不是WPF,所以没有“DataBind”功能。
你可以这样做:
然后
Not sure if you guys have tried all of the code that you've been posting or not, but you can't add items do a databound ComboBox. This is winforms, not WPF, so there is no "DataBind" function.
You could do this:
Then
您可以尝试这样的操作:(
编辑以反映 Brad_Z 的出色建议)
这将允许您绑定到此函数的结果,如下所示:
或者像这样,如果您希望为初始项目:
You could try something like this:
(Edited to reflect Brad_Z's excellent suggestion)
This will allow you to bind to the results of this function like this:
or like this, if you wish to specify a different value for the initial item:
(请参阅我对问题的编辑,我在其中澄清了我不想绑定到字符串集合)。
经过更多的摆弄后,下面的怪物似乎起作用了。 combo1.SelectedItem 是对象类型,并且将是 DBNull 或(装箱?)枚举值。 这段代码值得推荐吗?
编辑:我发现亚当和安德鲁的方法可以很容易地适应做同样的事情。 多谢你们!
(Please see my edit to the question where I clarified that I don't want to bind to a collection of strings).
After more fiddling, the following monstrosity seems to work. combo1.SelectedItem is of type object and will either be a DBNull or a (boxed?) enum value. Is this code advisable?
Edit: I see Adam and Andrew's methods could easily be adapted to do the same thing. Thanks guys!