I've created custom structure Date which internally uses DateTime but it's prevents from storing current day time:
public struct Date
{
private readonly DateTime _dateTime;
public Date(int year, int month, int day)
{
_dateTime = new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc);
}
public override string ToString()
{
return _dateTime.ToString();
}
public static Date Parse(string input)
{
return new Date(DateTime.Parse(input));
}
//other class members
}
This solution works fine for me, but I'm stuck when I want to take Date from user. When I'm binding this type to DatePicker I can't set or get values in binded property:
<DatePicker SelectedDate="{Binding Date}"/>
Property:
public Date Date
{
get { return _date; }
set
{
_date = value;
OnPropertyChanged("Date");
}
}
Is there some smart way to have "bindable custom structure"?
This won´t work, cause the property SelectedDate of the DatePicker control is of type Nullable<DateTime> and the runtime cannot implicitly converter your Date struct to a DateTime struct.
What you can do is to implement an IValueConverter to convert a DateTime to your Date struct.
For me i would not use my own struct to represent a Date value. You should change your property to DateTime and use the Date property of the DateTime if you are only interested in the Date value.
public DateTime Date
{
get { return _date; }
set
{
_date = value.Date;
OnPropertyChanged("Date");
}
}
If you want to keep your Date struct then use a IValueConverter, that you assign to your binding to convert Date to DateTime and vice versa.
public class DateToDateTimeConverter : IValueConverter{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
// convert Date to DateTime
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
//convert DateTime to Date
}
}
XAML:
<DatePicker SelectedDate="{Binding Date, Converter={StaticResource dateToDateTimeConverter}}"/>
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