Since it is not possible to insert values into a DataGridTemplateColumn. I found some suggestions for creating my own column class derived from a DataGridBoundColumn. The example below adds a DatePicker to a column without using a template.
However, this example does not allow me to manually set the value using DatePicker, and I'm not sure why. I think there is something with a binding. It will load the date values that I bind to them initially, so that it is halfway there.
Interestingly, with some other helper classes, I can also insert dates that were origianl's target. I just didn’t want to break anything. :-)
Any ideas on how to choose the selected datepicker value correctly?
class MyDateColumn : DataGridBoundColumn
{
public string DateFormat { get; set; }
protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue)
{
DatePicker dp = editingElement as DatePicker;
if (dp != null)
{
dp.SelectedDate = DateTime.Parse(uneditedValue.ToString());
}
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
DatePicker dp = new DatePicker();
Binding b = new Binding();
Binding bb = this.Binding as Binding;
b.Path = bb.Path;
b.Source = DatePicker.SelectedDateProperty;
if (DateFormat != null)
{
DateTimeConverter dtc = new DateTimeConverter();
b.Converter = dtc;
b.ConverterParameter = DateFormat;
}
dp.SetBinding(DatePicker.SelectedDateProperty, this.Binding);
return dp;
}
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
TextBlock txt = new TextBlock();
Binding b = new Binding();
Binding bb = this.Binding as Binding;
b.Path = bb.Path;
b.Source = cell.DataContext;
if (DateFormat != null)
{
DateTimeConverter dtc = new DateTimeConverter();
b.Converter = dtc;
b.ConverterParameter = DateFormat;
}
txt.SetBinding(TextBlock.TextProperty, this.Binding);
return txt;
}
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
DatePicker dp = editingElement as DatePicker;
if (dp != null)
{
DateTime? dt = dp.SelectedDate;
if (dt.HasValue)
return dt.Value;
}
return DateTime.Today;
}
protected override bool CommitCellEdit(FrameworkElement editingElement)
{
DatePicker dp = editingElement as DatePicker;
dp.SelectedDate = DateTime.Today.AddYears(1);
return true;
}
}