0

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" />
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mathi901
  • 235
  • 3
  • 14
  • http://stackoverflow.com/questions/12984522/how-to-get-iskeydown-method-to-work-in-c-sharp this might be helpful. – Emilia Tyl Jul 29 '15 at 11:39

3 Answers3

1

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" />
Bijington
  • 3,661
  • 5
  • 35
  • 52
0

First of all, you shouldn't use textchanged event for that. Instead use KeyDown event

private void txtConteudo_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyData == Key.Back)
    {
        txtConteudo.Text = "";
    }
}
Developer Nation
  • 374
  • 3
  • 4
  • 20
0

Try this

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