Use the same click Event for various C# WPF buttons

Asked

Viewed 712 times

2

I’m doing a C# project using WPF, which has many buttons. Is there any way to identify which button was clicked so you don’t need to click_event for each Button?

  • You can only have one button_Click(Object Sender, Routedeventargs and) and inside the event, identify the button through some property, for example the e.Content

  • Man, I read it all wrong. I think I’m falling asleep D=

1 answer

2


Yes.

You use the object sender to find out which button called the event.

private void button_Click(object sender, RoutedEventArgs e){
    var button = (Button)sender; //Aqui será instanciado o botão que chamou o evento

    // A partir daqui você pode usar uma propriedade, para saber qual foi o botão que chamou o evento.
    // Eu costumo definir uma tag para o botão e usá-las nesses caso, algo como:

    if(button.Tag == 1){
        // fazer algo
    }

    // Mas também pode ser usada a propriedade Name

    if(button.Name == "btSalvar"){
        // fazer algo
    }

}
  • Thanks, that’s just what I needed! = D

  • Glad I could help =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.