我有autogeneratedcolumns datagridgrid。这是我用于定义数据网格的xml代码:
<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Stretch" Name="dataGrid1" VerticalAlignment="Stretch"
AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn">
现在,我正在扫描每一列,如果列类型等于System.DateTime,我想添加一个日期选择器,其选择值等于单元格中的值:
private void dataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
// Modify the header of the Name column.
if (e.PropertyType.ToString() == "System.DateTime")
{
e.Column = new System.Windows.Controls.DatePicker();
}
}
但是当我这样做时,我收到此错误:
Cannot implicitly convert type 'System.Windows.Controls.DatePicker' to 'System.Windows.Controls.DataGridColumn
”
任何想法如何解决问题?
谢谢你提前。
答案 0 :(得分:2)
您可以将2个DataTemplates用作:
<DataTemplate x:Key="dueDateCellTemplate">
<TextBlock
Text="{Binding DueDate}"
Margin="5,4,5,4" />
</DataTemplate>
<DataTemplate x:Key="dueDateCellEditingTemplate">
<sdk:DatePicker
SelectedDate="{Binding DueDate, Mode=TwoWay}" />
</DataTemplate>
然后您可以在支票上编辑您的列:
private void dataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "System.DateTime")
{
// Create a new template column.
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.CellTemplate = (DataTemplate)Resources["dueDateCellTemplate"];
templateColumn.CellEditingTemplate = (DataTemplate)Resources["dueDateCellEditingTemplate"];
e.Column = templateColumn;
}
}