title: How do you create an element programmatically from a data template defined in XAML?
body: <p>I'm trying to create multiple button with text underneath and have them added to a Stackpanel in code during runtime. I create the buttons based on a List of data. Here's my code:</p>
  
  <p>XAML</p>
  
  <pre><code>&lt;StackPanel x:Name="MainSP" /&gt;
  </code></pre>
  
  <p>C#</p>
  
  <pre><code>foreach (item in ItemList)
  {
      Button newBtn = new Button();
      Image buttonImage = new Image();
      buttonImage.Width = 100;
      buttonImage.Height = 100;
      buttonImage.Stretch = Systems.Windows.Media.Stretch.Uniform;
      buttonImage.Source = new BitmapImage(pokemon.ImageURI);
      newBtn.Tag = item.Id;
      newBtn.Name = String.Format("{0}Button", item.Name);
      newBtn.Click += new RoutedEventHandler(newBtn_Click);
  
      FamilyStackPanel.Children.Add(newBtn);
  }
  </code></pre>
  
  <p>I know this is clunky programming. I really want to set up a ControlTemplate in XAML then reuse that when creating the buttons in code. Here's the XAML:</p>
  
  <pre><code>&lt;ControlTemplate x:Key="ButtomTemplate" TargetType="Button"&gt;
          &lt;Grid Height="108" Width="Auto" Margin = "6,6"&gt;
              &lt;Grid.RowDefinitions&gt;
                  &lt;RowDefinition Height="Auto"/&gt;
                  &lt;RowDefinition Height="*"/&gt;
              &lt;/Grid.RowDefinitions&gt;
              &lt;Image Width = "54" Height="54" Stretch="UniformToFill" Grid.Row="0"&gt;
                  &lt;Image.Source&gt;
                      &lt;BitmapImage UriSource="{Binding ImageUri}" CreateOptions="BackgroundCreation"/&gt;
                  &lt;/Image.Source&gt;
              &lt;/Image&gt;
              &lt;TextBlock Text="{Binding Name}"
                      Foreground ="{StaticResource PhoneAccentBrush}" /&gt;
          &lt;/Grid&gt;
  &lt;/ControlTemplate&gt;
  </code></pre>
  
  <p>I've tried using the controlTemplate like above and then for the bindings, I set the newbtn.DataContext in code.</p>
  
  <pre><code>foreach (Families item in ItemList)
  {
      Button newBtn = new Button();
      newBtn.Template = this.Resources["ButtonTemplate"] as ControlTemplate;
      newBtn.Tag = item.Id;
      newBtn.Name = String.Format("{0}Button", item.Name);
      newBtn.Click += new RoutedEventHandler(newBtn_Click);
      newBtn.DataContext = item;
  
      FamilyStackPanel.Children.Add(newBtn);
  }
  </code></pre>
  
  <p>For the data context I've also attempted <code>newBtn.DataContext = ItemList[itemIndex]</code> but that didn't seem to work. All I get is a blank screen.</p>
  
  <p>So I've figured it out through pure code behind button creation, but I'm trying to use XAML control templates to make it work. Have any ideas?</p>
  
  <p>Thank you!</p>