0

I have autogeneratedcolumns datagridgrid. This is my xml code for defining a datagrid:

<DataGrid AutoGenerateColumns="True"  HorizontalAlignment="Stretch"  Name="dataGrid1" VerticalAlignment="Stretch"  
              AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn">

Now, I am scanning each column and if column type is equal to System.DateTime, I want to add a datepicker with selected value equal to the value in the cell:

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

    }

But when I do this I get this error: Cannot implicitly convert type 'System.Windows.Controls.DatePicker' to 'System.Windows.Controls.DataGridColumn' Any ideas how to solve the problem? Thanks in advanced.

Amir
  • 625
  • 1
  • 11
  • 26

1 Answers1

2

You can have 2 DataTemplates as:

<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>

Then You can edit your column on check as like :

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;
            }            
  }
  • 1
    Thanks for the response. How can I bind a Datepicker to CellEditingTemplate ? And then set the SelectedDate to cell value? – Amir Oct 24 '12 at 05:03
  • So far it doesn't work. there is no values in the cells. But when I click on the cells it show a datepicker with today's date! – Amir Oct 24 '12 at 05:19
  • @ dbaseman: I have no idea how to implement that, can you guide me? – Amir Oct 24 '12 at 05:23
  • Still does NOT work, the cells are empty. As soon as I click on a cell, datepicker appears but when I choose a time it says: two-way binding requires path or xpath. – Amir Oct 24 '12 at 14:18