title: Create StackPanels dynamically and refer to any of them in code behind
body: <p>In its simplest form...</p>
  
  <p>I would like to create as many StackPanels as I want and then add Rectangles in them. Then to be able to change the Fill color of any one of the Rectangles when I click the Start Button for instance. All in Code Behind.</p>
  
  <p>Any help would be appreciated.</p>
  
  <p>For example, <strong>if our favorite beer wrote the framework</strong> I could do it like this:</p>
  
  <p>XAML:</p>
  
  <pre><code>&lt;Page
      x:Class="Test2.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:Test2"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"&gt;
  
      &lt;Grid Background="White"&gt;
          &lt;Grid.RowDefinitions&gt;
              &lt;RowDefinition Height="Auto"/&gt;
              &lt;RowDefinition Height="*"/&gt;
          &lt;/Grid.RowDefinitions&gt;
  
          &lt;StackPanel Orientation="Horizontal"&gt;
              &lt;Button Name="StartButton" Content="Start" Click="StartButton_Click" Height="30" Width="200" Margin="5"/&gt;
          &lt;/StackPanel&gt;
  
          &lt;StackPanel Grid.Row="1" Name="myStackPanel" VerticalAlignment="Top"/&gt;
  
      &lt;/Grid&gt;
  &lt;/Page&gt;
  </code></pre>
  
  <p>Code Behind:</p>
  
  <pre><code>namespace Test2
  {
      public sealed partial class MainPage : Page
      {
          public MainPage()
          {
              this.InitializeComponent();
  
              for (var i = 0; i &lt; 5; i++) // The 5 here could be any number
              {
                  myStackPanel.Children.Add(new StackPanel
                  {
                      Name = "myPanel" + i,
                      Orientation = Orientation.Horizontal
                  });
  
                  for (var j = 0; j &lt; 10; j++) // The 10 here could be any number
                  {
                      ("myPanel" + i).Children.Add(new Rectangle
                      {
                          Name = "myRectangle" + i + "-" + j,
                          Fill = new SolidColorBrush(Colors.Black),
                          Width = 20,
                          Height = 20,
                          Margin = new Thickness(1)
                      });
                  }
              }
          }
  
          private void StartButton_Click(object sender, RoutedEventArgs e)
          {
              // E.G. To change the Fill color of Rectangle4 in StackPanel2
  
              ("myRectangle" + 2 + "-" + 4).Fill = new SolidColorBrush(Colors.Red);
          }
      }
  }
  </code></pre>