【问题标题】:Is there a way to clear a TextBox's text without TextChanged firing?有没有办法在不触发 TextChanged 的​​情况下清除 TextBox 的文本?
【发布时间】:2014-01-18 14:35:14
【问题描述】:

在我的应用程序中,我想在某些情况下处理 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;
} 

【问题讨论】:

    标签: c# textbox event-handling textchanged


    【解决方案1】:

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

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

    在更复杂的情况下,最好尝试/finally 并在 finally 部分重新启用 TextChanged 事件

    【讨论】:

    • 我从来没有想过这个问题。非常感谢您的帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多