Access to children from StackPanel

Helmar Thiere 1 Reputation point
2022-05-31T06:48:33.773+00:00

Unfortunately I can't find a way to access the children of a StackPanel directly (without creating a parallel list).
E.g. here as a demo to change the background color of a border via index.

Border border;

        private void Button0_Click(object sender, RoutedEventArgs e)
        {
            border = new Border();
            border.Background = new SolidColorBrush(Colors.Red);
            _stack0.Children.Add(border);
            border.Width = 100;
            border.Height = 100;

            border = new Border();
            border.Background = new SolidColorBrush(Colors.Yellow);
            _stack0.Children.Add(border);
            border.Width = 75;
            border.Height = 75;

            border = new Border();
            border.Background = new SolidColorBrush(Colors.Green);
            _stack0.Children.Add(border);
            border.Width = 50;
            border.Height = 50;
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            _stack0.Children[0].Opacity = 0.5;
            //Change Background of Children[0] ???

        }
Developer technologies | Windows Presentation Foundation
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2022-05-31T07:11:58.297+00:00

    Try something like this:

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
       Border b = _stack0.Children[0] as Border;
       if( b != null) 
       {
          b.Background = . . .
       }
    }
    
    0 comments No comments

  2. Helmar Thiere 1 Reputation point
    2022-05-31T13:08:24.69+00:00

    Super, Thank You!

    0 comments No comments

  3. Helmar Thiere 1 Reputation point
    2022-05-31T13:08:26.84+00:00

    Super, Thank You!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.