修改ComboBox SelectedIndex而不在C#中触发事件

Jim*_*ell 8 c# events winforms

我的C#应用​​程序有comboBox一个SelectedIndexChanged事件.通常,我希望这个事件能够解雇,但有时候我需要事件才能解雇.我comboBox是MRU文件列表.如果发现列表中的文件不存在,则从该项中删除该项comboBox,并将其comboBox SelectedIndex设置为零.但是,将事件设置comboBox SelectedIndex为零会导致SelectedIndexChanged事件触发,在这种情况下会出现问题,因为它会导致某些UIF代码在事件处理程序中运行.是否有一种优雅的方法来禁用/启用C#表单控件的事件?谢谢.

Jim*_*ffa 15

使用启动eventhandler方法

ComboBox combo = sender as ComboBox;
if (combo.SelectedIndex == 0)
{
    return;
}
Run Code Online (Sandbox Code Playgroud)

如果问题是使用不同的事件处理程序,则可以先删除事件处理程序的事件注册.

combo.SelectedIndexChanged -= EventHandler<SelectedIndexChangedEventArgs> SomeEventHandler;
combo.SelectedIndex = 0;
combo.SelectedIndexChanged += EventHandler<SelectedIndexChangedEventArgs> SomeEventHandler;
Run Code Online (Sandbox Code Playgroud)


Les*_*ith 9

多年来我多次遇到过这种情况.我的解决方案是有一个名为_noise的类级变量,如果我知道我要更改组合索引或所选索引更改时触发的任何其他类似控件,我在代码中执行以下操作.

private bool _noise;
Run Code Online (Sandbox Code Playgroud)

这是控件事件处理程序的代码

private void cbTest_SelectedIndexChange(object sender, EventArgs e)
{
   if (_noise) return;

   // process the events code

   ...

}
Run Code Online (Sandbox Code Playgroud)


然后,当我知道我要更改索引时,我会执行以下操作:

_noise = true; // cause the handler to ignore the noise...


cbTest.Index = value;


_noise = false;  // let the event process again
Run Code Online (Sandbox Code Playgroud)


Mar*_*ata 5

我很惊讶没有更好的方法来做到这一点,但这就是我这样做的方式。我实际上使用了Tag大多数控件的字段,因此不必对控件进行子类化。我使用true/null作为值,因为null这是默认值。

当然,如果你实际使用Tag,你需要采取不同的做法......

在处理程序中:

 private void control_Event(object sender, EventArgs e)
 {
    if (control.Tag != null ) return;

    // process the events code

    ...

 }
Run Code Online (Sandbox Code Playgroud)

在主代码中

 try 
 {
    control.Tag = true;
    // set the control property
    control.Value = xxx;
or
    control.Index = xxx; 
or
    control.Checked = xxx;
    ...
 }
 finally 
 {
    control.Tag = null;
 }
Run Code Online (Sandbox Code Playgroud)