2014-01-18 62 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事件。非常感謝您的幫助。 :) –

相關問題