2012-11-01 134 views
2

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

任何帮助将不胜感激。

+0

简短的回答是否定的,你不能改变在.NET控件中触发的事件的顺序。但也许你不需要。你的用例是什么?也就是说,你在'TextChanged'中想要做什么,你需要知道'SelectedIndexChanged'是否已经被解雇? – ean5533

+0

但是文本被改变了......这就是为什么它被调用。似乎并不愚蠢。 –

+0

文字被改变_因为另一个项目被选中_。以错误的顺序告诉它是愚蠢的,因为它不能被理解。 – ygoe

回答

3

不,你不能改变的命令 - 这是硬编码到控制代码:

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

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

如果你对每个事件处理程序,并需要他们按照一定的顺序运行,你可以有 TextChanged事件查找SelectedIndexChanged事件发生的某些指示器,然后从SelectedIndexChanged处理程序中调用TextChanged处理程序,或者只让SelectedIndexChanged完成所有工作。

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

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;  
    } 

} 

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

0
if (SelectedIndex == -1) // only the text was changed. 
相关问题