按下Backspace键时删除TextBox内容C#

时间:2015-07-29 11:34:30

标签: c# textbox backspace

我按下退格键时尝试删除TextBox的内容,但它无法正常工作。代码:

private void txtConteudo_TextChanged(object sender, TextChangedEventArgs e)
    {
        if(Keyboard.IsKeyDown(Key.Back))
        {
            txtConteudo.Text = "";
        }
    }

文本框的xaml:

<TextBox x:Name="txtConteudo" Text="0" FontSize="16" IsReadOnly="True" Margin="10,5,16,139" TextChanged="txtConteudo_TextChanged" />

3 个答案:

答案 0 :(得分:1)

您想要使用PreviewKeyDown事件。尝试将当前代码更改为:

代码:

private void txtConteudo_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.Back))
    {
        txtConteudo.Text = "";
    }
}

的Xaml:

<TextBox x:Name="txtConteudo" Text="0" FontSize="16" IsReadOnly="True" Margin="10,5,16,139" PreviewKeyDown="txtConteudo_PreviewKeyDown" />

答案 1 :(得分:0)

首先,您不应该使用 textchanged event 。而是使用 KeyDown事件

private void txtConteudo_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyData == Key.Back)
    {
        txtConteudo.Text = "";
    }
}

答案 2 :(得分:0)

试试这个

private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 8)
            {
                textBox1.Text = "";
            }
        }