2014-01-18 63 views
2

在我的应用程序中,我想在某些情况下处理TextBox输入(例如,某些条件未填充),并且因为KeyDown仅适用于键盘输入,但并非实际从剪贴板粘贴(我不想去通过使用Win32调用这样做的麻烦),我想我只是处理我的主要TextBox的TextChanged事件中的一切。但是,当出现“错误”并且用户不能输入时,如果我打电话给TextBox.Clear();,TextChanged会再次触发,这是可以理解的,因此消息也会显示两次。这有点令人讨厌。任何方式我只能在这种情况下处理TextChanged?示例代码(内部txtMyText_TextChanged):有没有办法清除TextBox的文本没有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; 
} 

回答

5

什么断开变更前的事件处理程序,并重新连接之后?

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

在更复杂的情况下,最好是有一个try /终于在最后部分

+1

这从来没有过我的脑海里重新启用TextChanged事件。非常感谢您的帮助。 :) –

相关问题