Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Binding to a custom structure

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"?

like image 811
Miłosz Wierzbicki Avatar asked Dec 07 '25 00:12

Miłosz Wierzbicki


1 Answers

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}}"/>
like image 65
Jehof Avatar answered Dec 08 '25 16:12

Jehof