Since there is no way to paste values into a DataGridTemplateColumn. I found some suggestions for creating my own column class derived from DataGridBoundColumn. The sample below adds a DatePicker to the column without using a template.
However this sample does not allow me to manually set a value using the DatePicker and I'm not sure why. I'm thinking there is something with the binding. It will load date values that I bind to it initially so it's halfway there.
Interestingly enough using some other helper classes I'm able to paste dates as well which was the origianl purpose. I just didn't want to break anything else. :-)
Any ideas how to make the datepicker selected value bind properly?
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;
//return base.CommitCellEdit(editingElement);
}
}