title: How do you bind to a Grid in a ItemsPanel?
body: <p>I am building a custom control based on <code>ItemsControl</code>. I am trying to bind to the grid contained in the <code>ItemsPanelTemplate</code>. I cannot seem to get the binding correct. Any help is appreciated!</p>
  
  <pre><code>&lt;local:MyItemsControl Height="500" Width="500" Margin="50" gRow="1"&gt;
          &lt;ItemsControl.ItemsPanel&gt;
              &lt;ItemsPanelTemplate&gt;
  
                  &lt;Grid Background="Red" &gt;
                      &lt;Grid.RowDefinitions&gt;
                          &lt;RowDefinition Height="30"/&gt;
                          &lt;RowDefinition Height="30"/&gt;
                          &lt;RowDefinition Height="30"/&gt;
                          &lt;RowDefinition Height="30"/&gt;
                          &lt;RowDefinition Height="30"/&gt;
                      &lt;/Grid.RowDefinitions&gt;
                      &lt;Grid.ColumnDefinitions&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                          &lt;ColumnDefinition Width="*"/&gt;
                      &lt;/Grid.ColumnDefinitions&gt;
                  &lt;/Grid&gt;
              &lt;/ItemsPanelTemplate&gt;
          &lt;/ItemsControl.ItemsPanel&gt;
      &lt;/local:MyItemsControl&gt;
  </code></pre>
  
  <p>Here is my class:</p>
  
  <pre><code>public class MyItemsControl : ItemsControl
      {
          public MyItemsControl()
          {
              this.DefaultStyleKey = typeof(ItemsControl);
          }
  
          public int gRow { get; set; }
  
          protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
          {
              base.PrepareContainerForItemOverride(element, item);
              if (element is FrameworkElement)
              {
                  (element as ContentPresenter).SetBinding(Grid.RowProperty, new Binding {Source = item, Path = new PropertyPath("gRow")});
              }
  
          }
      }
  </code></pre>