lvlack
lvlack

Reputation: 61

WPF multiple buttons, same click function but different parameter

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?

Upvotes: 3

Views: 4402

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39976

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());
}

Upvotes: 7

Related Questions