简体   繁体   English

有什么办法不叫控制事件?

[英]Is there any way not to call Control Event?

Let's say there is event ComboBox_SelectedIndexChange something like this 假设有一个事件ComboBox_SelectedIndexChange这样的事情

private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
  //do something//
}

And i have a function which changes value of ComboBox. 而且我有一个功能,可以更改ComboBox的值。

Private void MyFunction()
{
   MyComboBox.Text = "New Value";
}

Can i make MyFunction prevent from calling the event MyComboBox_SelectedIndexChanged while changing the value of MyComboBox? 我可以让MyFunction防止在更改MyComboBox的值时调用事件MyComboBox_SelectedIndexChanged吗?

Can i make MyFunction prevent from calling the event MyComboBox_SelectedIndexChanged while changing the value of MyComboBox? 我可以让MyFunction防止在更改MyComboBox的值时调用事件MyComboBox_SelectedIndexChanged吗?

No, you cannot. 你不能。 You have two fundamental options, both of which accomplish the same thing: 您有两个基本选项,它们都可以完成相同的任务:

  1. You can unhook the event handler method from the control, set the value, and then reattach the event handler method to the control. 您可以从控件中解除事件处理程序方法的挂钩,设置值,然后将事件处理程序方法重新附加到控件。 For example: 例如:

     private void MyFunction() { MyComboBox.SelectedIndexChanged -= MyComboBox_SelectedIndexChanged; MyComboBox.Text = "New Value"; MyComboBox.SelectedIndexChanged += MyComboBox_SelectedIndexChanged; } 
  2. You can declare a class-level field that will keep track of whether the value was updated programmatically or by the user. 您可以声明一个类级别的字段,以跟踪该值是通过编程方式还是由用户更新。 Set the field when you want to update the combo box programmatically, and verify its value in the SelectedIndexChanged event handler method. 要以编程方式更新组合框时,请设置该字段,并在SelectedIndexChanged事件处理程序方法中验证其值。
    For example: 例如:

     private bool allowComboBoxChange = true; private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (allowComboBoxChange) { //do something } } private void MyFunction() { allowComboBoxChange = false; MyComboBox.Text = "New Value"; allowComboBoxChange = true; } 

You may attach or detach an event handler. 您可以附加或分离事件处理程序。

//attach the handler
MyComboBox.SelectedIndexChanged+=(sender,eventArgs)=>
{
  //code
};
//detach the handler
MyComboBox.SelectedIndexChanged-=(sender,eventArgs)=>
{
  //code
};

Or 要么

Private void MyFunction()
{
   comboBox1.SelectedIndexChanged -= new EventHandler(TestIt);
   MyComboBox.Text = "New Value";
   comboBox1.SelectedIndexChanged += new EventHandler(TestIt);
}

private void TestIt(object sender, EventArgs e)
{
  //do something//
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM