Declare textbox event in XAML

0

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.

    
asked by anonymous 09.08.2017 / 21:39

1 answer

3

You're making a huge mess.

First of all, KeyPressEventArgs is not an event is just a class used to pass parameters to the event of KeyPress .

So this does not exist. This class comes from Windows Forms, it does not make sense to try to use it because its element is not this namespace .

For WPF what is used is KeyEventArgs .

private void txtTara_KeyPress(object sender, KeyEventArgs e) { }

Second, there is no event KeyPress in WPF, you will have to use KeyDown .

Third, change the method name to txtTara_KeyPress . Because: 1) there already exists an element with this name (the component itself); and 2) this is the C # naming pattern.

And finally, you need to bind the event to the visual element. Somehow the visuals need to know there is an event triggered, there is no magic to figure it out.

To bind an event to a componenen, you need to declare in XAML.

For example:

<TextBox x:Name="txtTara" 
         HorizontalAlignment="Left" Height="23" Margin="161,130,0,0"  
         TextWrapping="Wrap" Text="0" VerticalAlignment="Top" 
         Width="120" KeyDown="txtTara_KeyPress"/>
    
09.08.2017 / 21:48