Search code examples
wpfdatagriddatatemplatedatatemplateselector

How to use DataTemplateSelector with a DataGridBoundColumn?


I followed the simple method described here and have a DataGrid with dynamically generated columns which allows DataTemplates to be used and bound dynamically.

        for (int i = 0; i < testDataGridSourceList.DataList[0].Count; i++)
        {
            var binding = new Binding(string.Format("[{0}]", i));
            CustomBoundColumn customBoundColumn = new CustomBoundColumn();
            customBoundColumn.Header = "Col" + i;
            customBoundColumn.Binding = binding;
            customBoundColumn.TemplateName = "CustomTemplate";
            TestControlDataGrid.TestDataGrid.Columns.Add(customBoundColumn);
        }

Each column is of type CustomBoundColumn which derives from DataGridBoundColumn

public class CustomBoundColumn : DataGridBoundColumn
{
    public string TemplateName { get; set; }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        var binding = new Binding(((Binding)Binding).Path.Path);
        binding.Source = dataItem;

        var content = new ContentControl();
        content.ContentTemplate = (DataTemplate)cell.FindResource(TemplateName);
        content.SetBinding(ContentControl.ContentProperty, binding);
        return content;
    }

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        return GenerateElement(cell, dataItem);
    }
}

I would now like to use a DataTemplateSelector to allow each row to use a different DataTemplate instead of just using the "CustomTemplate" shown in the first snippet. How can I do this?


Solution

  • In the end I replaced

    content.ContentTemplate = (DataTemplate)cell.FindResource(TemplateName);
    

    with

    content.ContentTemplateSelector = (DataTemplateSelector)cell.FindResource("templateSelector");
    

    where 'templateSelector' is the key of a DataTemplateSelector declared as a Static Resource in the XAML code. This works fine.