有没有办法在没有TextChanged触发的情况下清除TextBox的文本?

Dim*_*dis 3 c# textbox event-handling textchanged

在我的应用程序中,我想TextBox在某些情况下处理输入(例如,某些条件没有填充),因为KeyDown它仅对键盘输入有用,但不是从剪贴板实际粘贴(我不想经历麻烦无论如何使用Win32调用这样做,我想我只是处理我的主要TextBox TextChanged事件中的所有内容.但是,当有"错误"并且用户无法输入时,如果我要调用TextBox.Clear();它,TextChanged会再次触发,这是可以理解的,因此消息也会显示两次.那有点烦人.我只能在这种情况下处理TextChanged?示例代码(内部txtMyText_TextChanged):

if (txtMyOtherText.Text == string.Empty)
{
    MessageBox.Show("The other text field should not be empty.");

    txtMyText.Clear(); // This fires the TextChanged event a second time, which I don't want.

    return;
} 
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 6

如何在更改之前断开事件处理程序并在之后重新连接?

if (txtMyOtherText.Text == string.Empty)
{
    MessageBox.Show("The other text field should not be empty.");
    txtMyText.TextChanged -= textMyText_TextChanged;
    txtMyText.Clear(); 
    txtMyText.TextChanged += textMyText_TextChanged;
    return;
} 
Run Code Online (Sandbox Code Playgroud)

在更复杂的情况下,最好有一个try/finally并重新启用finally部分中的TextChanged事件