Question

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?

Était-ce utile?

La solution 2

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.

Autres conseils

Sorry for the late answer. I believe the solution is quite simple, just place a ContentPresenter in your "CustomTemplate" :

<DataTemplate x:Key="CustomTemplate">
    <ContentPresenter Content="{Binding}"
                      ContentTemplateSelector="{StaticResource myTemplateSelector}">
    </ContentPresenter>
</DataTemplate>

And there you go! You can now use a DataTemplateSelector. A good example here.

I made a custom column class that combines the DataGridBoundColumn with the DataGridTemplateColumn.

You can set Binding and Template on that column.

Here's the source: gist

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top