Using silverlight datepicker and timepicker togeth

2019-05-29 07:32发布

问题:

I'm using the Silverlight DatePicker and TimePicker from the toolkit together to allow a user to select a date and time. They are bound to the same DateTime value on a business object behind the scences. This mostly works okay, except when the date component is changed the time component is wiped. This is kinda logical but probably not the behaviour the user wanted.

There's a couple of ways I could hack my way round this:

  • Store the date and time components in different values (not that hacky but a little anonying as I'm going to store the resulting value as one field in a db)
  • Try and fix up the time component when the SelectedDateChanged event fires (which does seem a very hacky solution)

I'd like to be able to tell the DatePicker control: just leave the time component when you change date. Am I hoping for too much?

回答1:

I think, you can say DatePicker "Just leave the time component when you change date" using converter :). When you are binding DateTime to DatePicker converter stores value, and on ConvertBack returns without changes in Time part.

public class DateConverter : IValueConverter
{
    private DateTime _original;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        _original = (DateTime)value;
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = ((DateTime) value);
        return new DateTime(date.Year, date.Month, date.Day, _original.Hour, _original.Minute, _original.Second);
    }
}

XAML:

<sdk:DatePicker SelectedDate="{Binding Date, Mode=TwoWay, 
                Converter={StaticResource dateConverter}}" />

<input:TimePicker Value="{Binding Date, Mode=TwoWay}"/>