1

how do i set a buttons name when i created it in c# so i can call it later?

i have a a List of strings (Commands).

i loop over it an create a button for each item in the List.

       commands.ForEach(delegate (String i)
        {


            Button button = new Button()
            {
                Name = i,
                Tag = i,
                MaxWidth = 50,
                MaxHeight = 50,
                BorderBrush = null
            };


            button.Click += new RoutedEventHandler(button_Click);
            this.grid.Children.Add(button);

            Uri resourceUri = new Uri("led_Off.png", UriKind.Relative);
            StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);

            BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
            var brush = new ImageBrush();
            brush.ImageSource = temp;

            button.Background = brush;

        });

This loop works fine until i add the line Name = i

i am in a spot where these buttons were created and i now need to change some of there back ground images. is there a better way to call them then by there name?

Jyeomans
  • 71
  • 4

2 Answers2

0

Name should be a valid string: try Name = "button" + i.ToString() (FYI, Button Name cannot be just "1", it's an invalid Name). Also, Tag =i.ToString(). Hope this may help

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • Thanks, that did it! i have tried to solve this for over two days. i will accept the answer as soon as i can. – Jyeomans Mar 26 '16 at 14:52
  • You are welcome. I am glad it works for you. Please mark the answer accepted if you are satisfied with solution. Good luck with your project. Best regards, – Alexander Bell Mar 26 '16 at 14:55
  • yes the button name was ment to be "i" not 1 that was a typo on my part. thanks again. great help. – Jyeomans Mar 26 '16 at 15:07
0

Don't do it, use data binding and data templating with commands instead.

There is no reason to ever create any UI elements in a loop in WPF.

Edit: Just this.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400