Как использовать DataTemplateSelector с DataGridBoundColumn?

Я следовал простому методу, описанному здесь, и получил DataGrid с динамически генерируемыми столбцами, что позволяет использовать DataTemplates. и связаны динамически.

        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);
        }

Каждый столбец имеет тип CustomBoundColumn, производный от 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);
    }
}

Теперь я хотел бы использовать DataTemplateSelector, чтобы позволить каждой строке использовать другой DataTemplate, а не просто использовать «CustomTemplate», показанный в первом фрагменте. Как я могу это сделать?


person Caustix    schedule 01.10.2011    source источник
comment
Другой DataTemplate в зависимости от чего?   -  person Natxo    schedule 04.10.2011
comment
В зависимости от типа данных, отображаемых в этой строке (я заполняю список базовых классов, но каждая строка на самом деле может быть другим производным классом с несколькими дополнительными свойствами, которые я хотел бы использовать в DataTemplate)   -  person Caustix    schedule 10.10.2011


Ответы (3)


Извините за столь поздний ответ. Я считаю, что решение довольно простое, просто поместите ContentPresenter в свой «CustomTemplate»:

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

И вот! Теперь вы можете использовать DataTemplateSelector. Хороший пример здесь.

person Natxo    schedule 27.10.2011
comment
Я добился аналогичного результата без использования ContentPresenter. Хотя идея та же. +1 за ввод - person Caustix; 29.10.2011
comment
Ваша ссылка не работает, можете ли вы найти другой пример и вставить код, пожалуйста? - person VcDeveloper; 09.02.2017

В итоге заменил

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

с

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

где 'templateSelector' — это ключ DataTemplateSelector, объявленный как статический ресурс в коде XAML. Это прекрасно работает.

person Caustix    schedule 29.10.2011

Я создал собственный класс столбца, который объединяет DataGridBoundColumn с DataGridTemplateColumn.

Вы можете установить привязку и шаблон в этом столбце.

Вот источник: суть

person Owen Johnson    schedule 04.03.2014
comment
Как вы достигли возможности редактирования? Для меня приложение вылетает с Two-way binding requires Path or XPath., как только я начинаю редактирование. - person Gman; 29.05.2015
comment
Посмотрите на CellEditungTemplate - person Owen Johnson; 30.05.2015