问题
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.
<DataGrid
x:Name="dg"
AutoGenerateColumns="True"
ItemsSource="{Binding Path=Fields}"
AutoGeneratingColumn="dg_AutoGeneratingColumn">
</DataGrid>
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:
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);
}
The code for the the FieldCellTemplateSelector class is as follows:
public class FieldCellTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
return base.SelectTemplate(item, container);
}
}
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.
I can get the DataGridCell object by doing the following:
ContentPresenter presenter = container as ContentPresenter;
DataGridCell cell = presenter.Parent as DataGridCell;
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
Thanks in advance.
来源:https://stackoverflow.com/questions/8878454/force-datatemplatecell-with-celltemplateselector-in-wpf-datagrid-autogenerated-c