title: Binding from resources inside a DataTemplate
body: <p>Is there some way to get the <code>DataContext</code> of a <code>DataTemplate</code> to use in bindings within its resources?</p>
  
  <pre><code>&lt;DataTemplate x:Key="History"&gt;
    &lt;ItemsControl ItemsSource="{Binding History}"&gt;
      &lt;ItemsControl.Resources&gt;
        &lt;app:BitmapProvider x:Key="Converter" ShowDetails="True"
                            Type="{Binding Model.Type}" /&gt;
      &lt;/ItemsControl.Resources&gt;
      &lt;ItemsControl.ItemsPanel&gt;
        &lt;ItemsPanelTemplate&gt;
          &lt;StackPanel Orientation="Horizontal" IsItemsHost="True"/&gt;
        &lt;/ItemsPanelTemplate&gt;
      &lt;/ItemsControl.ItemsPanel&gt;
      &lt;ItemsControl.ItemTemplate&gt;
        &lt;DataTemplate&gt;
          &lt;Image Source="{Binding Data, Converter={StaticResource Converter}}" /&gt;
        &lt;/DataTemplate&gt;
      &lt;/ItemsControl.ItemTemplate&gt;
    &lt;/ItemsControl&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  
  <p>The above template is used as the <code>CellTemplate</code> of a <code>ListBox</code>.  The object at that level has two properties, <code>History</code> (containing a list of "historic info" objects) and <code>Model</code> (containing a bunch of other stuff, including <code>Type</code>).  I'm using an <code>ItemsControl</code> to display the historic items next to each other; I want to display an image for each one, and the image is obtained from the <code>BitmapProvider</code>, which is an <code>IValueConverter</code>.</p>
  
  <p>The converter needs two bits of info to obtain a result: one is the <code>Data</code> of the individual historic items, and the other is the <code>Type</code> of the whole collection.  An added complication is that constructing this particular converter (or changing the <code>Type</code> given to it) is expensive, so I don't want to put it at the level of the individual history item, or to use a <code>MultiBinding</code>, and I can't put it outside of the template because then it won't have access to the <code>Type</code>.</p>
  
  <p>Unfortunately, the above gives me the following error:</p>
  
  <p><em>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Model.Type; DataItem=null; target element is 'BitmapProvider' (HashCode=57142809); target property is 'Type' (type 'TypeDetails')</em></p>
  
  <p>Which I understand to mean that the resource can't figure out how to get the <code>DataContext</code> of the element it's contained within.</p>
  
  <p>(I have searched, and most of the answers I could find suggested moving it outside the template or using a <code>MultiBinding</code> instead -- neither of which would really work in this case, as far as I can tell, as I've explained above.  But I'd be delighted to be proven wrong, or given another alternative.)</p>