Olias Olias - 2 months ago 19
ASP.NET (C#) Question

CalendarDatePicker Binding Null Value

I´m using a CalendarDatePicker

<CalendarDatePicker x:Name="DatePick" DisplayMode="Decade" Date="{Binding DisplayValue, Mode=TwoWay}"/>


The Problem is when i bind the Date Property the Picker doesn't display the default Placeholder Text(select a date) anymore, instead it now displays 01.01.1916 if the property is null(The Property is always set null).

public DateTimeOffset? DisplayValue {get;set;}


if i manually put null as a value for Date, it now displays the PlaceholderText again.

DatePick.Date=null;


And the binding still works/i`m getting the desired values back when picking a date.
So is there an possibility to display the placeholder text without the using the codebehind?

Answer

I found a working solution. Therefore i expanded the default calendarDatePicker. I added an additional bindable Property which functions both as a defaultValue Setter for picking a Date and as a Setter for the Date value when needed.

public class CustomNewCalendarDatePicker : CalendarDatePicker
{
public DateTimeOffset? DefaultValue { get; set; }

public static readonly DependencyProperty DefaultValueProperty =
  DependencyProperty.Register("DefaultValue", typeof(DateTimeOffset), typeof(CustomNewCalendarDatePicker), new PropertyMetadata(null, (sender, e) =>
  {
    if ((DateTimeOffset?)e.NewValue != null && ((CustomNewCalendarDatePicker)sender).Date.Value.Date.Year == 1916)
    {
      ((CustomNewCalendarDatePicker)sender).SetDisplayDate((DateTimeOffset)e.NewValue);
      ((CustomNewCalendarDatePicker)sender).Date = null;
    }
    else if ((DateTimeOffset?)e.NewValue == null && ((CustomNewCalendarDatePicker)sender).Date.Value.Date.Year == 1916)
    {
      {
        ((CustomNewCalendarDatePicker)sender).SetDisplayDate(DateTimeOffset.Now);
        ((CustomNewCalendarDatePicker)sender).Date = null;
      }
    }
  }));
}