How do I declare the KeyPressEventArgs event of a textbox to work with this event in Code Behind? The code to run the event I have, I just can not declare the event, as I do with the Click, for example. This one I can. I found that for keypress, keydown, it was not necessary to declare, but when I create my event in Code Behind, it gives me error in the textbox. See my codes. XAML:
<TextBox x:Name="txtTara" HorizontalAlignment="Left" Height="23" Margin="161,130,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="120"/>
Code Behind:
private void txtTara(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.' || e.KeyChar == ',')
{
//troca o . pela virgula
e.KeyChar = ',';
//Verifica se já existe alguma vírgula na string
if (txtTara.Text.Contains(","))
{
e.Handled = true; // Caso exista, aborte
}
}
//aceita apenas números, tecla backspace.
else if (!char.IsNumber(e.KeyChar) && !(e.KeyChar == (char)Keys.Back))
{
e.Handled = true;
}
}
This code I copied here in SOpt.