按下退格键时删除文本框内容 C#

Delete TextBox content when Backspace key is pressed C#

我试图在按下退格键时删除 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" />

您想改为使用 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" />

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

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

试试这个

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