Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF multiple buttons, same click function but different parameter

Tags:

c#

.net

wpf

xaml

I want to make several buttons with the same click function but different parameter. Like this

XAML:

<Button Click="MyClickFunction(1)" Content="MyFunc(1)"/>
<Button Click="MyClickFunction(2)" Content="MyFunc(2)"/>
<Button Click="MyClickFunction(3)" Content="MyFunc(3)"/>
<Button Click="MyClickFunction(4)" Content="MyFunc(4)"/>

C#:

private void MyClickFunction(object sender, RoutedEventArgs e, int myParam)
{
    //do something with parameter e.g. MessageBox.Show()
    MessageBox.Show(myParam.ToString());
}

How to I pass the parameter in xaml tag or I will have to do it other ways?

like image 561
lvlack Avatar asked Jul 29 '26 05:07

lvlack


1 Answers

Use Tag property in the button. Like this:

<Button Click="MyClickFunction" Tag="1" Content="MyFunc(1)"/>
<Button Click="MyClickFunction" Tag="2" Content="MyFunc(2)"/>
<Button Click="MyClickFunction" Tag="3" Content="MyFunc(3)"/>
<Button Click="MyClickFunction" Tag="4" Content="MyFunc(4)"/>

And in the code behind:

private void MyClickFunction(object sender, RoutedEventArgs e)
{
    var tag = ((Button)sender).Tag;
    MessageBox.Show(tag.ToString());
}
like image 69
Salah Akbari Avatar answered Jul 31 '26 17:07

Salah Akbari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!