title: Force DataTemplateCell with CellTemplateSelector in WPF DataGrid Autogenerated columns
body: <p>I have a data grid to which I bind a DataTable. I don't know what rows or columns will be in the data table so I set the AutogenerateColumns property of the data grid to true. The only thing I do know for certain is that every cell in the data table will be of type Field and the Field class has a enum property called Type.</p>
  
  <pre><code>&lt;DataGrid
      x:Name="dg"
      AutoGenerateColumns="True"
      ItemsSource="{Binding Path=Fields}"
      AutoGeneratingColumn="dg_AutoGeneratingColumn"&gt;
  &lt;/DataGrid&gt;
  </code></pre>
  
  <p>What I want to do is to force all of the auto generated columns to be DataTemplateColumns which have the CellTemplateSelector property set to a FieldCellTemaplateSelector object. To do this I add the following code the AutoGeneratingColumn event:</p>
  
  <pre><code>private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
  {
      //cancel the auto generated column
      e.Cancel = true;
  
      //create a new template column with the CellTemplateSelector property set
      DataGridTemplateColumn dgtc = new DataGridTemplateColumn();
      dgtc.CellTemplateSelector = new FieldCellTemplateSelector();
      dgtc.IsReadOnly = true;
      dgtc.Header = e.Column.Header;
  
      //add column to data grid
      DataGrid dg = sender as DataGrid;
      dg.Columns.Add(dgtc);
  }
  </code></pre>
  
  <p>The code for the the FieldCellTemplateSelector class is as follows:</p>
  
  <pre><code>public class FieldCellTemplateSelector : DataTemplateSelector
  {
      public override DataTemplate SelectTemplate(object item, DependencyObject container)
      {
          return base.SelectTemplate(item, container);
      }
  }
  </code></pre>
  
  <p>In the SelectTemplate method I need to get the Field object that is contained in the cell and return the relevant data template based on the Type property of that field. The problem is that the item parameter that is passed is not of type Field, it is of type DataRowView. </p>
  
  <p>I can get the DataGridCell object by doing the following:</p>
  
  <pre><code>ContentPresenter presenter = container as ContentPresenter;
  DataGridCell cell = presenter.Parent as DataGridCell;
  </code></pre>
  
  <p>However, the data context of the cell is also of type DataRowView. What has happened to my Field? Has it disappeared? Can anyone let me know how to get at it or how I can achieve a solution to this problem</p>
  
  <p>Thanks in advance.</p>