It seems that the DisplayDate doesn't bind correctly when the DatePicker is inside a ControlTemplate.
This is how I bind the DisplayDate to the DatePicker through MVVM. But the DatePicker wont display the CustomDisplayDate correctly. It keep show the default display date which is DateTime.Now().
Keep in mind that this code does work if the DatePicker is not inside a ControlTemplate.
Any suggestions on how to solve this?
XAML code:
<Window.Resources>
<ControlTemplate x:Key="DateField">
<StackPanel>
<TextBlock Text="Custom Display Date:" />
<TextBlock Text="{Binding CustomDisplayDate}"/>
<DatePicker
SelectedDate="{Binding CustomSelectedDate}"
DisplayDate="{Binding CustomDisplayDate}"
HorizontalAlignment="Left"
VerticalAlignment="Top"/>
</StackPanel>
</ControlTemplate>
</Window.Resources>
<Grid>
<ContentControl Template="{StaticResource DateField}" />
</Grid>
and the ViewModel:
public class MainWindowViewModel
{
public MainWindowViewModel()
{
CustomDisplayDate = DateTime.Now.AddDays(5);
}
public DateTime? CustomSelectedDate { get; set; }
public DateTime CustomDisplayDate { get; set; }
}
I realize that this is pretty old but I just stumbled in to this same issue today. I'm not certain why this happens and I'm fairly certain I had my bindings established correctly.
I did find a work around, at least in my case. I wired up the PreparingCellForEdit event to my ViewModel. That method peeked examines the column to determine if the editing cell belongs to the correct column of datepickers and I also examined if the date it is bound to is null which told me that it was a new row. I can then grab the datepicker and set its DisplayDate from code.
private void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
{
DataGridColumn sourceColumn = e.Column;
DataGridRow sourceRow = e.Row;
ScheduleDate data = (ScheduleDate) sourceRow.DataContext;
if (string.Equals(sourceColumn.Header.ToString(), "Work Date") && !data.WorkDate.HasValue)
{
var dp = e.EditingElement.GetVisualChild<DatePicker>() as DatePicker;
dp.DisplayDate = this.WorkDate;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With