Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF How to know the current button pressed among multiple buttons

Tags:

button

wpf

I am having multiple buttons with contents 1, 2, 3, 4, 5... like this. All buttons are using same function on Click event.

<Button Content="1" Height="30" Name="button1" Width="30" Click="calculate"/>
<Button Content="2" Height="30" Name="button2" Width="30" Click="calculate"/>
<Button Content="3" Height="30" Name="button3" Width="30" Click="calculate"/>
<Button Content="4" Height="30" Name="button4" Width="30" Click="calculate"/>
<Button Content="5" Height="30" Name="button5" Width="30" Click="calculate"/>

How could i know which button is pressed in calculate function ? I want to get the content from the button which is pressed.

private void calculate(object sender, RoutedEventArgs e)
        {

        }

Thank You.

like image 473
KillerFish Avatar asked Apr 06 '11 12:04

KillerFish


2 Answers

You can get the content property using this in your function -

string content = (sender as Button).Content.ToString();
like image 61
Rohit Vats Avatar answered Mar 28 '23 04:03

Rohit Vats


If you place Name or x:Name attributes in your XAML for your buttons, you can then use the native object.Equals() without having to cast or dereference. This also protects you from having to double edit your code, and possibly forgetting to edit in both places when the Content of the control is changed.

Given

<Button Name="btnOne" ... />
<Button Name="btnTwo" ... />

then

if (sender.Equals(btnOne)) {...}
if (sender.Equals(btnTwo)) {...}
like image 35
ergohack Avatar answered Mar 28 '23 04:03

ergohack