我这里有一个愚蠢的问题,但我无法解决。问题是当我以编程方式将组合框与数据绑定(bind)时,它会自动设置 selectedItem 但我使用属性字段添加项目时它不会设置 selectedItem。
我的问题是如何在不触发选定事件的情况下以编程方式绑定(bind)项目(这意味着它的行为类似于使用默认情况下不设置 selectedItem 的属性进行绑定(bind))?提前致谢。
以编程方式设置的示例
string[] items = {"Apple", "Orange", "Banana"}; comboBox1.DataSource = items;
当程序运行时它看起来像这样(选择默认值是 Apple):
使用属性字段设置项目的示例 (VS 2013)
然后它看起来像这样(未选择默认值):
最佳答案
您可以先取消订阅然后再订阅该事件,因为我认为当您使用 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/