我遵循此处描述的简单方法,并拥有一个带有动态生成列的 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);
}
每列都是从 DataGridBoundColumn 派生的 CustomBoundColumn 类型
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”。我怎样才能做到这一点?