title: How to set ItemsPanelTemplate to a dynamically created Grid in code behind
body: <p>I've got this <code>UserControl</code> defined in <code>XAML</code> and would like to set the <code>ItemsPanelTemplate</code> dynamically in my code behind class (not in the <code>XAML</code> like in the example):</p>
  
  <pre><code>&lt;UserControl&gt;
      &lt;ItemsControl x:Name="Items"&gt;
          &lt;ItemsControl.ItemsPanel&gt;
              &lt;ItemsPanelTemplate&gt;
                  &lt;Grid&gt; &lt;!-- I want to add this Grid definition in code behind --&gt;
                      &lt;Grid.ColumnDefinitions&gt;
                          &lt;ColumnDefinition /&gt;
                      &lt;/Grid.ColumnDefinitions&gt;
                      &lt;Grid.RowDefinitions&gt;
                          &lt;RowDefinition /&gt;
                      &lt;/Grid.RowDefinitions&gt;
                  &lt;/Grid&gt;
              &lt;/ItemsPanelTemplate&gt;
         &lt;/ItemsControl.ItemsPanel&gt;
      &lt;/ItemsControl&gt;
  &lt;/UserControl&gt;
  </code></pre>
  
  <p>I tried something like</p>
  
  <pre><code>this.Items.ItemsPanel.Template = new Grid();
  </code></pre>
  
  <p>but failed miserably. Any help?</p>
  
  <p><strong>Background:</strong>
  I only know the number of grid columns and rows at runtime.</p>