是否可以更改活动顺序?

时间:2012-11-01 21:42:33

标签: c# events combobox selectedindexchanged textchanged

是否可以更改某些事件的调用顺序?例如,我有一个ComboBox,当选择被更改时,我希望在调用TextChanged事件之前调用SelectedIndexChanged事件。我的诚实的看法是,在SelectedIndexChanged事件之前调用TextChanged事件是非常愚蠢的,因为它阻止我知道是否因为选择了新项而调用了TextChanged事件。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

不,你不能改变顺序 - 它被硬编码到控制代码中:

// from http://referencesource.microsoft.com
if (IsHandleCreated) { 
    OnTextChanged(EventArgs.Empty);
} 

OnSelectedItemChanged(EventArgs.Empty);
OnSelectedIndexChanged(EventArgs.Empty); 

如果你有每个事件的处理程序,并且需要它们以特定顺序运行,你可以拥有 TextChanged事件查找SelectedIndexChanged事件发生的某个指示符,然后从TextChanged处理程序调用{​​{1}}处理程序,或者让SelectedIndexChanged执行所有操作工作。

这取决于为什么您需要它们按特定顺序运行。

答案 1 :(得分:0)

你可以做些什么,但解决方案并不是一个好的解决方案。你肯定会混淆任何一个可能在将来维护你的应用程序的人,也许你自己也会忘记你做过的事情。但无论如何它在这里:

这个想法是让相同的函数处理这两个事件,跟踪索引的旧值和&文本,以便您可以相应地处理事件的处理方式

// two fields to keep the previous values of Text and SelectedIndex
private string _oldText = string.Empty;
private int _oldIndex = -2;
.
// somewhere in your code where you subscribe to the events
this.ComboBox1.SelectedIndexChanged += 
new System.EventHandler(ComboBox1_SelectedIndexChanged_AND_TextChanged);
this.ComboBox1.TextChanged+= 
new System.EventHandler(ComboBox1_SelectedIndexChanged_AND_TextChanged);
.
.

/// <summary>
///  Shared event handler for SelectedIndexChanged and TextChanged events.
///  In case both index and text change at the same time, index change
///  will be handled first.
/// </summary>
private void ComboBox1_SelectedIndexChanged_AND_TextChanged(object sender, 
        System.EventArgs e)
{

   ComboBox comboBox = (ComboBox) sender;

   // in your case, this will execute on TextChanged but 
   // it will actually handle the selected index change
   if(_oldIndex != comboBox.SelectedIndex) 
   {
      // do what you need to do here ...   

      // set the current index to this index 
      // so this code doesn't exeute again
      oldIndex = comboBox.SelectedIndex;
   }
   // this will execute on SelecteIndexChanged but
   // it will actually handle the TextChanged event
   else if(_oldText != comboBox.Test) 
   {
      // do what you need to ...

      // set the current text to old text
      // so this code doesn't exeute again 
      _oldText = comboBox.Text;      
   }

}

请注意,当单独触发事件时,此代码仍然有效 - 仅更改文本或仅更改索引。

答案 2 :(得分:0)

if ( SelectedIndex == -1 )  // only the text was changed.