Force DataTemplateCell with CellTemplateSelector in WPF DataGrid Auto Generated Columns

I have a data grid that I am binding a DataTable to. 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 know for sure is that every cell in the data table will be of type Field, and the Field class has an enum property called Type.

<DataGrid
    x:Name="dg"
    AutoGenerateColumns="True"
    ItemsSource="{Binding Path=Fields}"
    AutoGeneratingColumn="dg_AutoGeneratingColumn">
</DataGrid>

      

I want all auto-generated columns to be DataTemplateColumns that have their CellTemplateSelector property set to a FieldCellTemaplateSelector object. To do this, I add the following code: 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 FieldCellTemplateSelector class looks like this:

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 the cell contains and return the appropriate data template based on the Type property of that field. The problem is that the passed parameter item 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 cell's data context is also of type DataRowView. What happened to my field? He disappeared? Can anyone let me know how to do this or how can I solve the problem?

Thanks in advance.

0


source to share


1 answer


I had the same problem. Found the answer at this link.



http://social.msdn.microsoft.com/Forums/en/wpf/thread/8b2e94b7-3c44-4642-8acc-851de5285062

+1


source







All Articles