我的 C# 应用程序有一个
comboBox
和 SelectedIndexChanged
事件。通常,我希望该事件触发,但有时我需要该事件不触发。我的comboBox
是一个MRU文件列表。如果发现列表中的文件不存在,则将从 comboBox
中删除该项目,并将 comboBox
SelectedIndex
设置为零。但是,将 comboBox
SelectedIndex
设置为零会导致 SelectedIndexChanged
事件触发,在本例中这是有问题的,因为它会导致一些 UIF 代码在事件处理程序中运行。是否有一种优雅的方式来禁用/启用 C# 表单控件的事件?谢谢。
使用
启动事件处理程序方法ComboBox combo = sender as ComboBox;
if (combo.SelectedIndex == 0)
{
return;
}
如果问题出在不同的事件处理程序上,您可以先删除事件处理程序的事件注册。
combo.SelectedIndexChanged -= EventHandler<SelectedIndexChangedEventArgs> SomeEventHandler;
combo.SelectedIndex = 0;
combo.SelectedIndexChanged += EventHandler<SelectedIndexChangedEventArgs> SomeEventHandler;
这些年来我已经多次遇到过这种情况。我的解决方案是有一个名为 _noise 的类级别变量,如果我知道我要更改组合的索引或在选定索引更改时触发的任何其他类似控件,我会在代码中执行以下操作。
private bool _noise;
这是控件事件处理程序的代码
private void cbTest_SelectedIndexChange(object sender, EventArgs e)
{
if (_noise) return;
// process the events code
...
}
然后,当我知道我要更改索引时,我会执行以下操作:
_noise = true; // cause the handler to ignore the noise...
cbTest.Index = value;
_noise = false; // let the event process again
我很惊讶没有更好的方法来做到这一点,但这就是我这样做的方式。实际上,我使用大多数控件的
Tag
字段,因此我不必对控件进行子类化。我使用 true
/null
作为值,因为 null
是默认值。
当然,如果你实际使用
Tag
,你需要采取不同的做法...
在处理程序中:
private void control_Event(object sender, EventArgs e)
{
if (control.Tag != null ) return;
// process the events code
...
}
在主代码中
try
{
control.Tag = true;
// set the control property
control.Value = xxx;
or
control.Index = xxx;
or
control.Checked = xxx;
...
}
finally
{
control.Tag = null;
}
一种(相当难看)的方法是在删除条目的代码中设置一个标志,然后在
SelectedIndexChanged
处理程序中检查:
if (!deletedEntry)
{
// Do stuff
}
deletedEntry = false;
更好的方法可能是在删除方法开始时删除
SelectedIndexChanged
事件处理程序并在结束时恢复它。这样您的代码就不会知道索引已更改。
有更好的方法!
combo_box = QComboBox() # your combobox
combo_box.blockSignals(True)
combo_box.setCurrentIndex(self, ix)
combo_box.blockSignals(False)
您可以在更改
SelectedIndex
之前取消订阅活动,然后再重新订阅。
private void changeIndex(int index)
{
comboBox.SelectedIndexChanged -= comboBox_SelectedIndexChanged; // Unsubscribe from event
comboBox.SelectedIndex = index; // Set to desired index
comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged; // Subscribe back to the event
}