Can I shoehorn a DateTimePicker date and a Textbox "Time" into a DateTime?

I have a group of components like so:

<StackPanel Orientation="Horizontal" >
    <Label>Between</Label>
    <DatePicker Name="dtpFrom" ></DatePicker>
    <TextBox Name="timeFrom" MinWidth="60" />
    <Label>and</Label>
    <DatePicker Name="dtpTo"></DatePicker>
    <TextBox Name="timeTo"
               MinWidth="60" />
</StackPanel>

where the user can select the date and set the "From" date and time and the "To" date and time.

I want to combine these (the date portion of the DatePicker with the corresponding time portion represented within the TextBox) into a DateTime value. e.g., with:

DateTime dtFrom;

...I want to be able to do something like (pseudocode):

dtFrom = (DateTime) dtpFrom.Date + Convert.ToTime(timeFrom);

Is there a way to do this?

Upvotes: 3

Views: 868

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

I would recommend handling this within your DataContext (ie: ViewModel), and binding to two separate properties. These could easily map to an underlying DateTime.

For example:

// In ViewModel
private DateTime dateTime;

public DateTime Date
{
    get { return dateTime.Date; }
    set
    {
        if (value != dateTime.Date)
        {
            dateTime = value.Date + dateTime.TimeOfDay;
            RaisePropertyChanged("Date");
        }
    }
}

public TimeSpan Time
{
    get { return dateTime.TimeOfDay; }
    set
    {
        if (value != dateTime.TimeOfDay)
        {
            dateTime = dateTime.Date + value;
            RaisePropertyChanged("Time");
        }
    }
}

This would let you bind each control to the appropriate property, but still maintain everything within a single DateTime instance.

Upvotes: 5

Related Questions