假设有类似的事件ComboBox_SelectedIndexChange
private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//do something//
}
我有一个改变组合框值的函数。
Private void MyFunction()
{
MyComboBox.Text = "New Value";
}
我可以让MyFunction在更改MyComboBox的值时阻止调用事件MyComboBox_SelectedIndexChanged吗?
我可以让MyFunction在更改MyComboBox的值时阻止调用事件MyComboBox_SelectedIndexChanged吗?
不,你不能。您有两个基本选项,这两个选项都可以完成相同的任务:
-
您可以将事件处理程序方法从控件中取消挂钩,设置值,然后将事件处理方法重新附加到控件。例如:
private void MyFunction() { MyComboBox.SelectedIndexChanged -= MyComboBox_SelectedIndexChanged; MyComboBox.Text = "New Value"; MyComboBox.SelectedIndexChanged += MyComboBox_SelectedIndexChanged; }
-
您可以声明一个类级字段,该字段将跟踪值是以编程方式更新的还是由用户更新的。当您希望以编程方式更新组合框时,请设置该字段,并在
SelectedIndexChanged
事件处理程序方法中验证其值
例如:private bool allowComboBoxChange = true; private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (allowComboBoxChange) { //do something } } private void MyFunction() { allowComboBoxChange = false; MyComboBox.Text = "New Value"; allowComboBoxChange = true; }
您可以附加或分离事件处理程序。
//attach the handler
MyComboBox.SelectedIndexChanged+=(sender,eventArgs)=>
{
//code
};
//detach the handler
MyComboBox.SelectedIndexChanged-=(sender,eventArgs)=>
{
//code
};
或
Private void MyFunction()
{
comboBox1.SelectedIndexChanged -= new EventHandler(TestIt);
MyComboBox.Text = "New Value";
comboBox1.SelectedIndexChanged += new EventHandler(TestIt);
}
private void TestIt(object sender, EventArgs e)
{
//do something//
}