我最近遇到了这个问题并以这种方式解决了它:
我们可以继承类DataGridBoundColumn
public class DataGridProcessContainerColumn : DataGridBoundColumn
{
public DataTemplate ContentTemplate { get; set; }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
throw new NotImplementedException();
}
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var control = new ContentControl();
control.ContentTemplate = ContentTemplate;
BindingOperations.SetBinding(control, ContentControl.ContentProperty, Binding);
return control;
}
}
接下来,在生成列的事件处理程序中,我执行以下操作:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataTemplate template = null;
// Four lines below replace the DataTemplateSelector
// You need to select the desired template according to your conditions
if (e.PropertyType.IsAssignableFrom(typeof(IEnumerable<MyClass2>)))
template = (DataTemplate)Resources["MyClass2CollectionTemplate"];
else if (e.PropertyType.IsAssignableFrom(typeof(MyClass2)))
template = (DataTemplate)Resources["MyClass2Template"];
if (template != null)
{
var col = new DataGridProcessContainerColumn();
col.Binding = (e.Column as DataGridBoundColumn).Binding;
col.ContentTemplate = template;
col.Header = e.Column.Header;
e.Column = col;
}
}
在窗口的资源中,我有相应的模板。
可以通过 DataTemplateSelector 来做,但是没有时间。