2

是否可以更改调用某些事件的顺序?for instance, I have a ComboBox and when a selection is changed, I would like the SelectedIndexChanged event to be called before the TextChanged event is called. 老实说,在 SelectedIndexChanged 事件之前调用 TextChanged 事件是非常愚蠢的,因为它使我无法知道是否因为选择了新项目而调用了 TextChanged 事件。

任何帮助将非常感激。

4

3 回答 3

3

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

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

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

如果您有每个事件的处理程序并需要它们以特定顺序运行,您可以让 TextChanged事件查找事件发生的一些指示符,然后从处理程序SelectedIndexChanged调用处理程序,或者只是完成所有工作。TextChangedSelectedIndexChangedSelectedIndexChanged

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

于 2012-11-01T21:50:21.637 回答
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;      
   }

}

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

于 2012-11-02T01:04:41.803 回答
0
if ( SelectedIndex == -1 )  // only the text was changed.
于 2013-11-16T17:35:21.527 回答