Reputation: 1967
I have a CalendarDatePicker whose Date property is bound to a converter. I don't want it to show the date if the date is default(01-01-0001)
My code
class DateTimeToCalendarDateTimeOffsetConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
try
{
DateTime date = (DateTime)value;
return new DateTimeOffset(date);
}
catch (Exception ex)
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
try
{
DateTimeOffset dto = (DateTimeOffset)value;
return dto.DateTime;
}
catch (Exception ex)
{
return DateTime.MinValue;
}
}
}
But by default it set's todays date. What value can I set to clear the date?
Upvotes: 0
Views: 520
Reputation: 16652
From the discussion we had earlier, I think you wanted to set the the Date
of the CalendarDatePicker
according to the value which is got from a server, but at first this value is set to "0001-01-01" by default.
So you can do it like this:
<Page.Resources>
<local:DateTimeToCalendarDateTimeOffsetConverter x:Key="cvt" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<CalendarDatePicker x:Name="picker" Date="{x:Bind Path=dateTime,Converter={StaticResource cvt}, Mode=TwoWay}" />
</Grid>
code behind:
private DateTime dateTime;
public MainPage()
{
this.InitializeComponent();
dateTime = new DateTime(0001, 01, 01);
}
This variable dateTime
is fake by me and is set in the code behind, and the converter is like this:
public class DateTimeToCalendarDateTimeOffsetConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var date = (DateTime)value;
if (date == new DateTime(0001, 01, 01))
{
return null;
}
return new DateTimeOffset?(date);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
var dto = (DateTimeOffset)value;
return dto.DateTime;
}
}
But be aware that the Date
is constrained by MinDate
and MaxDate
, if Date
is smaller than MinDate
, the value is set to MinDate
. If the Date
is greater than MaxDate
, the value is set to MaxDate
. So if you set the date here for example "0010-01-02", and your MinDate
is set to "2000-01-01", when return this date in your Converter
, the CalendarDatePicker
will show "01/01/2000".
For more information about this control, you can refer to CalendarDatePicker class.
Upvotes: 1