WPF How to find out the current button pressed between several buttons

I have several buttons with contents 1, 2, 3, 4, 5 ... like this. All buttons use the same function in the 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 can I find out which button is pressed in the count function? I want to get the content with the button pressed.

 private void calculate(object sender, RoutedEventArgs e) { } 

Thanks.

+4
source share
3 answers

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

 string content = (sender as Button).Content.ToString(); 
+11
source

If you put Name or x:Name attributes on your XAML for your buttons, you can use your own .Equals () object without having to throw or dereference. It also protects you from having to double code editing and possibly forget to edit in both places when you change the Content of the control.

Considering

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

then

 if (sender.Equals(btnOne)) {...} if (sender.Equals(btnTwo)) {...} 
+1
source

I am dealing with this problem by attaching an object to the tooltip property of a button. Then you can return it as follows:

  void EditMe (object sender, RoutedEventArgs e)
 {
     Button x = sender as Button;

     if (x! = null)
     {
         int id = (x.ToolTip as TT) .Id;
     }
 }

The TT object in this example looks like this:

  public class TT
         {
             public int Id {get;  set;  }
             public string Text {get;  set;  }
             public override string ToString ()
             {
                 return Text;
             }
         }

Displays hint text in the user interface and makes Id available in the click handler.

0
source

Source: https://habr.com/ru/post/1346914/


All Articles