Interact / Search Button for your Tag using WPF

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 Random function:

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 the background it?

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

I know I could do it one by one:

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

But it would not be right.

    
asked by anonymous 15.10.2015 / 23:25

3 answers

0

I found the answer the way I wanted 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!

    
16.10.2015 / 17:29
2

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

BTN[numero].Background = Brushes.Red;

I do not know how to do this in WPF, maybe this question in the OS will help you. It seems to have [to create with C # code and not XAML.

    
15.10.2015 / 23:33
1

I found this answer in SOen that refers to this class in code.google.

The class declares several methods of extension that allow you to search for a Child within a (Control) Parent (1) . The search can be done by type or type + criterion.

In your case, assuming all the buttons are in the same StackPanel, to find the button with the = 20 tag would look like this:

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

    
16.10.2015 / 12:54