Search code examples
c#textboxbackspace

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. The code:

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

The xaml of the textbox:

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

Solution

  • You want to use the PreviewKeyDown event instead. Try changing your current code to:

    Code:

    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" />