2
votes

This seems like it should be easy, but I haven't found an easy solution. I understand that I can have a CalendarDatePicker, DatePicker, etc, or I can have a TimePicker. I could place both on my page and bind to two separate properties, which themselves notify a DateTime property I care about which takes the Date (year, day, month) from the first picker, and the time from the second picker. emphasized text But that seems totally hackish. Is there a way to bind to a single DateTime object while picking a Date AND Time? I.E. I really just want to combine a DatePicker/CalendarDatePicker and a TimePicker into one logical XAML control that binds to a single DateTime object.

3
What stops you from creating a usercontrol that contains both and expose a single DateTime dependency property? - Justin XL

3 Answers

1
votes

You could try this simple function i wrote to combine your date and time. It functions by removing the default time in your DatePicker and adding the time from TimePicker to that variable.

private static DateTime CombineDateAndTime(DateTime dateObj,DateTime timeObj)
    {
        DateTime newDateTime;

        //get timespan from the date object
        TimeSpan spanInDate = dateObj.TimeOfDay;

        //subtract it to set date objects time to 0:00
        dateObj = dateObj.Subtract(spanInDate);

        //now add your newTime to date object
        newDateTime = dateObj.Add(timeObj.TimeOfDay);

        //return new value
        return newDateTime;
    }

Hope this helps.

0
votes
// code behind
DateTime date;
TimeSpan time
{
  get => date.TimeOfDay;
  set
  {
    date = date.AddTicks(value.Ticks);
  }
}

// xaml
<DatePicker Date={x:Bind date, Converter={StaticResource DateTimeToOffsetConverter}}" 
/>
<TimePicker Time={X:Bind time}" />
-1
votes

I have found the following code helpful:-

    int rex01=  t21.Date.Value.Year;                      
    int rex02 = t21.Date.Value.Month;        
    int rex03 = t21.Date.Value.Day;            
    int rex04 = t22.Time.Hours;           
    int rex05 = t22.Time.Minutes;        
    int rex06 = t22.Time.Seconds;  

    DateTime T02 = new DateTime(rex01, rex02, rex03, rex04, rex05, rex06);

Please note t21 is a DatePicker and t22 is a TimePicker. Currently used with respect to SQLite and UWP.