Hans Kalmanl
Hans Kalmanl

Reputation: 21

How to create a single click event for multiple buttons in .NET MAUI

I have created a simple application where I have many buttons and I want to create just one click event for all the buttons, so what's the logic in xamarin forms or .net maui?

Upvotes: 2

Views: 3834

Answers (1)

Asfend
Asfend

Reputation: 2089

Let's say you have two buttons just like this:

<Button Clicked="EventClickedHandler"/>
<Button Clicked="EventClickedHandler"/>

Now just add the Class id inside these button controls like this

<Button Clicked="EventClickedHandler" ClassId="1"/>
<Button Clicked="EventClickedHandler" ClassId="2"/>

Then inside the click event handler you can write the following code:

private void EventClickedHandler(object sender, EventArgs e) {
    var button = (Button)sender;
    var classId = button.ClassId;
    // This will give you the value / classId of your button which you'll press
    DisplayAlert("Hi", classId.ToString(), "Alright");
}

Upvotes: 6

Related Questions