Search code examples
c#wpfbuttonstackpanel

Get the number of a certain Button in stack panel


Hey I would like to create a stack panel with multiple buttons in it and when I press one, it tells me which button it is. Like when I press the second button from the top, I get the number 2 back and so on.

The buttons are created with this loop:

for (int i = 0; i < LBresponse.Items.Count; i++)
{
  System.Windows.Controls.Button BTclear = new Button();
  BTclear.Content = "Clear";
  BTclear.Width = 50;
  BTclear.Height = 20;
  BTclear.HorizontalAlignment = HorizontalAlignment.Right;
  BTclear.Click += Button_Click;
  BTclear.IsEnabled = true;
  STPresponse.Children.Add(BTclear);
}

I could do it with the location of the button but I hope there is a better solution.

One Idea would be to put the number into the context when the button is created but this would not be pretty.


Solution

  • You could store the number or index somewhere, for example in the Tag property:

    for (int i = 0; i<LBresponse.Items.Count; i++)
    {
        System.Windows.Controls.Button BTclear = new Button();
        BTclear.Tag = i;
        BTclear.Content = "Clear";
        BTclear.Width = 50;
        BTclear.Height = 20;
        BTclear.HorizontalAlignment = HorizontalAlignment.Right;
        BTclear.Click += (ss, ee) => 
        {
            MessageBox.Show(((Button)ss).Tag.ToString());
        };
        BTclear.IsEnabled = true;
        STPresponse.Children.Add(BTclear);
    }