简体   繁体   English

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

[英]Delete TextBox content when Backspace key is pressed C#

I'm trying to delete the content of a TextBox when the backspace key is pressed, but it is not working. 当试图按退格键时,我试图删除TextBox的内容,但是它不起作用。 The code: 编码:

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

The xaml of the textbox: 文本框的xaml:

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

You want to use the PreviewKeyDown event instead. 您想改用PreviewKeyDown事件。 Try changing your current code to: 尝试将当前代码更改为:

Code: 码:

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

Xaml: Xaml:

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

First of all, you shouldn't use textchanged event for that. 首先,您不应该为此使用textchanged事件 Instead use KeyDown event 而是使用KeyDown事件

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

Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM