c# - 以编程方式绑定(bind)数据源时,组合框选择事件自动触发 C#

标签 c# combobox

我这里有一个愚蠢的问题,但我无法解决。问题是当我以编程方式将组合框与数据绑定(bind)时,它会自动设置 selectedItem 但我使用属性字段添加项目时它不会设置 selectedItem。

我的问题是如何在不触发选定事件的情况下以编程方式绑定(bind)项目(这意味着它的行为类似于使用默认情况下不设置 selectedItem 的属性进行绑定(bind))?提前致谢。

以编程方式设置的示例

string[] items = {"Apple", "Orange", "Banana"}; comboBox1.DataSource = items;

当程序运行时它看起来像这样(选择默认值是 Apple):

enter image description here

使用属性字段设置项目的示例 (VS 2013)

enter image description here

然后它看起来像这样(未选择默认值):

enter image description here

最佳答案

您可以先取消订阅然后再订阅该事件,因为我认为当您使用 VisualStudio 中的属性字段设置数据时,所有设置都将在您订阅事件之前应用。

//unsubscribe the event handler (change the name of the event handler to your real name)
ComboBox1.SelectedIndexChanged -= ComboBox1_SelectedIndexChanged

//do your initialization
string[] items = {"Apple", "Orange", "Banana"}; 
comboBox1.DataSource = items;
comboBox1.SelectedIndex = -1;

//subscribe to it again
ComboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged

关于c# - 以编程方式绑定(bind)数据源时,组合框选择事件自动触发 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19244145/

相关文章:

c# - 将图片插值为特定颜色

c# - 合并空检查和模式匹配的 'if'语句时出错

.net - sendmessage api 选择组合框控件的特定索引

MVVM SelectionChanged 组合框不调用 'Set'

c# - ActiveMQ 服务故障转移和数据库故障转移

c# - .NET Core 中 Assembly.GetEntryAssembly() 的等价物是什么?

c# - 如何正确锁定值类型?

combobox - JavaFX组合框不刷新可见行数

javascript - Extjs4 转换组合框不会在表单提交时发送 value 属性

java - 从另一个类设置组合框