Interact/Search Button by its Tag using WPF

Asked

Viewed 210 times

0

I have a screen with 25 buttons and would like to interact with the buttons through the code.

For example, a number is generated using the function Random:

Random rdn = new Random();
numero = rdn.Next(0,25);

Let’s say the result was 20. How do I call this button that has the tag 20 and then change the color of background his?

myButton(????).Background = Brushes.Red;

I know I could do one by one:

        if (numero == 1)
        {
            BTN_1.Background = Brushes.Red;
        }
        if (numero == 2)
        {
            BTN_2.Background = Brushes.Red;
        }

But it wouldn’t be right.

3 answers

2

Basically I’d have to turn these buttons BTN_1, BTN_2, etc. on a vector of buttons. So it would have a BTN[1], BTN[2], etc. (I would change the names of the buttons, but it’s taste). So you have an index that can be applied the number that was drawn.

BTN[numero].Background = Brushes.Red;

I put in the Github for future reference.

I don’t know how to do this in WPF, maybe that question in the OR help you. It seems to have[to create with C# and not XAML code.

  • I found the answer... @bigown. Should I answer my own question? I don’t know if that’s correct. Thank you

  • @Ayo yes, please.

1

I found this reply on the Soen which refers to this class in the google code..

The class declares several extension methods that allow searching for a Son within a (Control)Parent(1). The search can be made by type or type + criterion.

In your case, assuming that all buttons are on the same Stackpanel, to find the button with the tag = 20 would be like this:

var myButton = stackPanel.FindChild<Button>(button => (int)button.Tag == 20);
myButton.Background = Brushes.Red;

(1) More specifically a Dependencyobject

0


I found the answer the way I’d like it to be.

string str = "00";
foreach (Control c in Grid.Children)
{
   if (c is Button && c.Tag.ToString() == str)
      {
          ((Button)c).Background = Brushes.Red;
      }
}

thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.